Skip to content

Commit e896215

Browse files
committed
add solution of problem 160: intersection of two linked lists
1 parent 792f419 commit e896215

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
Write a program to find the node at which the intersection of two singly linked lists begins.
2+
3+
4+
For example, the following two linked lists:
5+
6+
A: a1 → a2
7+
8+
c1 → c2 → c3
9+
10+
B: b1 → b2 → b3
11+
begin to intersect at node c1.
12+
13+
14+
Notes:
15+
16+
- If the two linked lists have no intersection at all, return `null`.
17+
- The linked lists must retain their original structure after the function returns.
18+
- You may assume there are no cycles anywhere in the entire linked structure.
19+
- Your code should preferably run in O(n) time and use only O(1) memory.
Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* public class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) {
7+
* val = x;
8+
* next = null;
9+
* }
10+
* }
11+
*/
12+
public class Solution {
13+
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
14+
if (headA == null || headB == null)
15+
return null;
16+
17+
ListNode currNodeA = headA;
18+
ListNode currNodeB = headB;
19+
20+
int lenA = 0;
21+
while (currNodeA != null) {
22+
currNodeA = currNodeA.next;
23+
lenA++;
24+
}
25+
26+
int lenB = 0;
27+
while (currNodeB != null) {
28+
currNodeB = currNodeB.next;
29+
lenB++;
30+
}
31+
32+
int diff = 0;
33+
34+
if (lenA > lenB) {
35+
currNodeA = headA;
36+
currNodeB = headB;
37+
diff = lenA - lenB;
38+
} else {
39+
currNodeA = headB;
40+
currNodeB = headA;
41+
diff = lenB - lenA;
42+
}
43+
44+
while (diff-- > 0) {
45+
currNodeA = currNodeA.next;
46+
}
47+
48+
ListNode result = null;
49+
50+
while (currNodeA != null && currNodeB != null) {
51+
if (currNodeA != currNodeB) {
52+
currNodeA = currNodeA.next;
53+
currNodeB = currNodeB.next;
54+
} else {
55+
result = currNodeA;
56+
break;
57+
}
58+
}
59+
60+
return result;
61+
}
62+
}

0 commit comments

Comments
 (0)