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

160. Intersection of Two Linked Lists

时间:2016-05-20 00:57:00      阅读:120      评论: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.

题目大意:查找2个链表相交的第一个交点

 

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
 9     int a,b,i;
10     struct ListNode *acur;
11     struct ListNode *bcur;
12     acur = headA;
13     bcur = headB;
14     a = b = 0;
15     while(acur != NULL || bcur != NULL)         //计算2个链表的长度
16     {
17         if(acur != NULL)
18         {
19             a++;
20             acur = acur->next;
21         }
22         if(bcur != NULL)
23         {
24             b++;
25             bcur = bcur->next;
26         }
27     }
28     acur = headA;                   
29     bcur = headB;
30     if(a > b)                      //长的先走|a-b|步,让2个链表的剩下的长度一样
31     {
32         i = a-b;
33         while(i)
34         {
35             acur = acur->next;
36             i--;
37         }
38     }
39     else
40     {
41         i = b - a;
42         while(i)
43         {
44             bcur = bcur->next;
45             i--;
46         }
47     }
48     while(acur != NULL)            //判断2个链表的第一个相交的结点
49     {
50         if(acur == bcur)
51             break;
52         acur = acur->next;
53         bcur = bcur->next;
54     }
55     if(acur != NULL)
56         return acur;
57     return NULL;
58     
59 }

 

160. Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/boluo007/p/5510583.html

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