160. Intersection of Two Linked Lists

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

寻找两个链表的交叉点。

让A的尾部和B的头,B的尾部和A的头连起来,两条链表就一样长了。

到达交叉点的时候,分别走过了A+C+B和B+C+A的路程,要是A=B,则只需要走第一段就好了。

 1 class Solution {
 2 public:
 3     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
 4         ListNode *p1 = headA;
 5         ListNode *p2 = headB;
 6         while (p1 != p2) {
 7             p1 = p1? p1->next: headB;
 8             p2 = p2? p2->next: headA;
 9         }
10         return p1;
11     }
12 };

 

posted @ 2018-03-27 10:13  Zzz...y  阅读(125)  评论(0)    收藏  举报