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;
        }
    };
  • 相关阅读:
    loaded some nib but the view outlet was not set
    指标评比
    IOS DEVELOP FOR DUMMIES
    软件测试题二
    javascript select
    DOM节点类型详解
    mysql操作
    UVA 10055
    solutions for 'No Suitable Driver Found For Jdbc'
    解决git中文乱码问题
  • 原文地址:https://www.cnblogs.com/lancelod/p/4375828.html
Copyright © 2011-2022 走看看