[LeetCode系列] 双单链表共同节点搜索问题

找到两个单链表的共同节点.

举例来说, 下面两个链表A和B:

A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3

共同节点为c1.

 

分析:

共同节点距离A,B的起点headA, headB的距离差为定值, 等于它们的各自总长的差值, 我们只需要求出这个差值, 把两个链表的头移动到距离c1相等距离的起点处即可.

代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        int deltaLength = getLengthOfList(headA) - getLengthOfList(headB);
        // A > B
        if (deltaLength > 0)
        {
            while (deltaLength-- > 0) headA = headA->next;
        }
        // A < B
        else if (deltaLength < 0)
        {
            while (deltaLength++ < 0) headB = headB->next;
        }
        // now A and B has the same distance to intersection node
        while (NULL != headA && NULL != headB)
        {
            if (headA == headB)
                return headA;
            headA = headA->next;
            headB = headB->next;
        }
        return NULL;
    }
    
    int getLengthOfList(ListNode *head)
    {
        int res = 0;
        while (NULL != head)
        {
            res++;
            head = head->next;
        }
        return res;
    }
};

 

posted @ 2015-03-29 16:22  Lancelod_Liu  阅读(345)  评论(0编辑  收藏  举报