-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetIntersectionNode.java
More file actions
79 lines (73 loc) · 2.04 KB
/
getIntersectionNode.java
File metadata and controls
79 lines (73 loc) · 2.04 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/**
* Author : WindAsMe
* File : getIntersectionNode.java
* Time : Create on 18-6-3
* Location : ../Home/JavaForLeeCode2/getIntersectionNode.java
* Function : LeeCode No.160
*/
public class getIntersectionNode {
private static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
private static ListNode getIntersectionNodeResult(ListNode headA, ListNode headB) {
int aLength = 0;
int bLength = 0;
ListNode tempA = headA;
ListNode tempB = headB;
while (tempA != null){
aLength += 1;
tempA = tempA.next;
}
while (tempB != null){
bLength += 1;
tempB = tempB.next;
}
System.out.println(aLength + " " + bLength);
tempA = headA;
tempB = headB;
if (aLength >= bLength){
while (aLength != bLength){
if (tempA == tempB){
return tempA;
} else {
tempA = tempA.next;
aLength--;
}
}
} else {
while (aLength != bLength){
if (tempA == tempB){
return tempA;
} else {
tempB = tempB.next;
bLength--;
}
}
}
System.out.println(aLength + " " + bLength);
while (aLength != 0){
if (tempA == tempB) {
return tempA;
} else {
tempA = tempA.next;
tempB = tempB.next;
aLength -= 1;
}
}
return null;
}
public static void main(String[] args){
ListNode a = new ListNode(1);
a.next = new ListNode(2);
a.next.next = new ListNode(5);
ListNode b = new ListNode(3);
b.next = new ListNode(5);
ListNode n = getIntersectionNodeResult(a, b);
System.out.println(n.val);
}
}