zoukankan      html  css  js  c++  java
  • [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;
        }
    };
  • 相关阅读:
    Windows Phone 7 利用计时器DispatcherTimer创建时钟
    杭电1163 Eddy's digital Roots
    随感1
    杭电 1194 Beat the Spread!
    杭电 1017 A Mathematical Curiosity
    杭电1202 The calculation of GPA
    关于递归的思想
    杭电1197 Specialized FourDigit Numbers
    杭电 1062 Text Reverse
    杭电1196 Lowest Bit
  • 原文地址:https://www.cnblogs.com/lancelod/p/4375828.html
Copyright © 2011-2022 走看看