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

 链表检测环

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;
}

 

posted @ 2016-03-31 00:03  brayden  阅读(186)  评论(0编辑  收藏  举报