[LeetCode 题解]:Intersection of Two Linked Lists

前言

 

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

 

1.题目描述

Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array.

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
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则作者保留追究法律责任的权利。  若本文对你有所帮助,您的关注推荐是我们分享知识的动力!
posted @ 2014-11-27 22:29  Double_win  阅读(218)  评论(0编辑  收藏  举报