码迷,mamicode.com
首页 > 其他好文 > 详细

Intersection of Two Linked Lists

时间:2015-06-18 11:20:39      阅读:81      评论:0      收藏: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.

 

Credits:
Special thanks to @stellari for adding this problem and creating all test cases.

 

Hide Tags

 Linked List

这道题是说有两个链表在某一点就合二为一,找到这个点。

所以,正常的只要按序遍历整个单链表即可。

我们注意到链表长度可能不同,所以可以让长度长的链表先走两个链表长度差的长度,再开始比较每个元素。

还有如果最后一个节点不同那个按照题意,则两个链表没有相交的节点

技术分享
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
12         int lenA = 1;
13         int lenB = 1;
14         ListNode *pa = headA;
15         ListNode *pb = headB;
16         if(headA == NULL ||headB == NULL) return NULL;
17         while(pa->next)
18         {
19             lenA++;
20             pa = pa->next;
21         }
22         while(pb->next)
23         {
24             lenB++;
25             pb = pb->next;
26         }
27         if(pa != pb) return NULL;
28         if(lenA > lenB)
29         {
30             for(int i =0;i<lenA-lenB;i++)
31             {
32                 headA = headA->next;
33             }
34         }
35         else if(lenB > lenA)
36         {
37             for(int i = 0;i < lenB-lenA;i++)
38             {
39                 headB = headB->next;
40             }
41         }
42         
43         while(headA && headB)
44         {
45             if(headA != headB)
46             {
47                 headA=headA->next;
48                 headB=headB->next;
49             }
50             else
51                 return headA;
52         }
53         
54     }
55 };
View Code

 

Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/chdxiaoming/p/4584976.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!