[LeetCode 题解]:Intersection of Two Linked Lists

前言

 

【LeetCode 题解】系列传送门:  http://www.cnblogs.com/double-win/category/573499.html

 

1.题目描述

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.

2. 题意

寻找两个链表的交点。

提示:

1. 如果两个链表没有交集,那么返回NULL。

2. 链表的结果不能发生变化。

3. 两个链表都没有环。

4. 请给出O(n)时间复杂度、O(1)空间复杂度的解法。

3. 思路

分别统计链表A和链表B的长度。

如果两个链表有交集,那么从交点CP开始,后续的所有节点都应该相同。如图所示C1->C2->C3.

两个链表不同的节点分别为a1,a2; b1,b2,b3;

比较两个链表的长度la,lb;

假设la>lb,那么链表A先遍历la-lb节点。从la-lb节点开始,两个链表的长度就相同了。然后依次比较各自节点是否相同,直到找到交点或者到达链表尾部。

4: 解法

class Solution {

public:

    int getListLen(ListNode *head){

        int len=0;

        ListNode *root=head;

        while(root){

            root=root->next;

            len++;

        }

        return len;

    }

    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {

        int alen=getListLen(headA),blen=getListLen(headB);

        ListNode *la=headA,*lb=headB;

        if(alen>blen){

            while(alen!=blen){

                la=la->next;

                alen--;

            }

        }

        if(alen<blen){

            while(alen!=blen){

                lb=lb->next;

                blen--;

            }

        }

        while(la!=lb){

            la=la->next;

            lb=lb->next;

        }

        if(!la||!lb){

            return NULL;

        }else{

            return la;

        }

    }

};

作者:Double_Win
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则作者保留追究法律责任的权利。   若本文对你有所帮助,您的关注推荐是我们分享知识的动力!

你可能感兴趣的:(intersect)