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

Intersection of Two Linked Lists

时间:2015-11-16 22:25:43      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

1. Title

Intersection of Two Linked Lists

2. Http address

https://leetcode.com/problems/intersection-of-two-linked-lists/

3. The question

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.

4. My code (AC)

  

 1     // Accepted
 2       public static ListNode getIntersectionNode(ListNode headA, ListNode headB) {
 3   
 4           if( headA == null || headB == null)
 5               return null;
 6           if( headA == headB)
 7               return headA;
 8           
 9           int lenA,lenB,distance;
10           ListNode p,q;
11           lenA = 0;
12           p = headA;
13           while( p != null)
14           {
15               lenA++;
16               p = p.next;
17           }
18           
19           lenB = 0;
20           q = headB;
21           while( q != null)
22           {
23               lenB++;
24               q = q.next;
25           }
26           
27           if( lenA >=lenB)
28           {
29               distance = lenA - lenB;
30               p = headA;
31               for(int i = 1; i <= distance; i++)
32               {
33                   p = p.next;
34               }
35               q = headB;
36               while( p != null && q != null && p != q)
37               {
38                   p = p.next;
39                   q = q.next;
40               }
41               return p;
42           }else{
43               distance = lenB - lenA;
44               p = headB;
45               for(int i = 1; i <= distance; i++)
46               {
47                   p = p.next;
48               }
49               q = headA;
50               while( p != null && q != null && p != q)
51               {
52                   p = p.next;
53                   q = q.next;
54               }
55               return p;
56           }
57           
58       }

 

Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/ordili/p/4970021.html

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