码迷,mamicode.com
首页 > 其他好文 > 详细

小程序 - 链表检测环/链表是否交叉 等

时间:2016-03-31 01:49:24      阅读:132      评论:0      收藏:0      [点我收藏+]

标签:

 链表检测环

int cycleExists(Node *head)
{
        Node *fast, *slow;
        if (head == NULL)
                return 0;
        for (slow = head, fast = head->next; fast && fast->next; 
            fast = fast->next->next, slow = slow->next)
                if (slow == fast)
                        return 1;
        return 0;
}

链表是否交叉

int listOverlapped(Node *list1, Node *list2)
{
    if (!list1 || !list2)
        return 0;
    for (; list1->next; list1 = list1->next);
    for (; list2->next; list2 = list2->next);
    return list1 == list2;
}

两个链表第一个公共节点

Node* firstCommonNode(Node *list1, Node *list2)
{
    int num1, num2;
    Node *n1, *n2;
    if (!list1 || !list2)
        return NULL;
    for (num1 = 0, n1 = list1; n1->next; num1++, n1 = n1->next);
    for (num2 = 0, n2 = list2; n2->next; num2++, n2 = n2->next);
    if (n1 != n2)
        return NULL;
    if (num1 > num2)
        for (num1 -= num2; num1 > 0; num1--, list1 = list1->next);
    else
        for (num2 -= num1; num2 > 0; num2--, list2 = list2->next);
    for (; list1 != list2; list1 = list1->next, list2 = list2->next);
    return list1;
}

 

小程序 - 链表检测环/链表是否交叉 等

标签:

原文地址:http://www.cnblogs.com/brayden/p/5339546.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!