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

LeetCode – Refresh – Intersection of Two Linked Lists

时间:2015-03-20 06:57:04      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

Find the common length part, then check with two pointers.

 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         if (!headA || !headB) return NULL;
13         int la = 1, lb = 1;
14         ListNode *runner = headA;
15         while (runner->next) {
16             runner = runner->next;
17             la++;
18         }
19         runner = headB;
20         while (runner->next) {
21             runner = runner->next;
22             lb++;
23         }
24         if (la > lb) {
25             while (la > lb) {
26                 headA = headA->next;
27                 la--;
28             }
29         } else {
30             while (lb > la) {
31                 headB = headB->next;
32                 lb--;
33             }
34         }
35         while (headA && headA->val != headB->val) {
36             headA = headA->next;
37             headB = headB->next;
38         }
39         return headA;
40     }
41 };

 

LeetCode – Refresh – Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4352636.html

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