-
Notifications
You must be signed in to change notification settings - Fork 1
/
160.intersection-of-two-linked-lists.java
57 lines (55 loc) · 1.21 KB
/
160.intersection-of-two-linked-lists.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* @lc app=leetcode id=160 lang=java
*
* [160] Intersection of Two Linked Lists
*/
// @lc code=start
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode curA = headA;
ListNode curB = headB;
int lenA = 0, lenB = 0;
while (curA != null) {
curA = curA.next;
lenA++;
}
while (curB!= null) {
curB = curB.next;
lenB++;
}
curA = headA;
curB = headB;
if (lenB > lenA) {
int tmp = lenA;
lenA = lenB;
lenB = tmp;
ListNode tmpNode = curA;
curA = curB;
curB = tmpNode;
}
int gap = lenA - lenB;
while (gap-- > 0) {
curA = curA.next;
}
while (curA != null) {
if (curA == curB) {
return curA;
}
curA = curA.next;
curB = curB.next;
}
return null;
}
}
// @lc code=end