导航

LeetCode 160. Intersection of Two Linked Lists

Posted on 2016-08-07 19:04  CSU蛋李  阅读(178)  评论(0编辑  收藏  举报

这个题目较容易,我的想法是先比较两个链表的长度,我们要找到的交叉点是不可能为长的链表的前面超长的部分的,

 

所以要比较的就是两者之间较短的部分

Write a program to find the node at which the intersection of two singly linked lists begins.

 

For example, the following two linked lists:

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

begin to intersect at node c1.

 

Notes:

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • You may assume there are no cycles anywhere in the entire linked structure.
  • Your code should preferably run in O(n) time and use only O(1) memory
    /**
     * 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) {
            size_t lengthA=0, lengthB=0,minus=0;
            ListNode *pA=headA, *pB=headB,*IntersectionNode=NULL;
            while (pA != NULL)
            {
                ++lengthA;
                pA = pA->next;
            }
            while (pB != NULL)
            {
                ++lengthB;
                pB = pB->next;
            }
            if (lengthA > lengthB)
            {
                pA = headA;
                pB = headB;
                minus = lengthA - lengthB;
                while (minus--)
                {
                    pA = pA->next;
                }
                while (pA != NULL&&pB != NULL)
                {
                    if (pA->val == pB->val&&IntersectionNode==NULL)
                        IntersectionNode = pA;
                    if (pA->val != pB->val)
                        IntersectionNode = NULL;
                    pA = pA->next;
                    pB = pB->next;
                }
                return IntersectionNode;
            }
            else
            {
                pA = headA;
                pB = headB;
                minus = lengthB - lengthA;
                while (minus--)
                {
                    pB = pB->next;
                }
                while (pA != NULL&&pB != NULL)
                {
                    if (pA->val == pB->val&&IntersectionNode == NULL)
                        IntersectionNode = pA;
                    if (pA->val != pB->val)
                        IntersectionNode = NULL;
                    pA = pA->next;
                    pB = pB->next;
                }
                return IntersectionNode;
            }
        }
    };
  •