File tree 1 file changed +63
-0
lines changed
1 file changed +63
-0
lines changed Original file line number Diff line number Diff line change
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
+
15
+ int lenA = getLinkedListLength (headA );
16
+ int lenB = getLinkedListLength (headB );
17
+
18
+ ListNode head1 = headA ;
19
+ ListNode head2 = headB ;
20
+
21
+ if (lenA > lenB ){
22
+ int diff = lenA - lenB ;
23
+ head1 = moveList (diff , head1 );
24
+ }
25
+ else {
26
+ int diff = lenB - lenA ;
27
+ head2 = moveList (diff , head2 );
28
+ }
29
+
30
+ while (head1 != null ){
31
+ if (head1 == head2 ){
32
+ return head1 ;
33
+ }
34
+ else if (head1 .next == head2 .next ){
35
+ return head1 .next ;
36
+ }
37
+ head1 = head1 .next ;
38
+ head2 = head2 .next ;
39
+ }
40
+
41
+ return null ;
42
+ }
43
+
44
+ public int getLinkedListLength (ListNode head ){
45
+ ListNode currentHead = head ;
46
+ int len = 0 ;
47
+
48
+ while (currentHead != null ){
49
+ currentHead = currentHead .next ;
50
+ len ++;
51
+ }
52
+
53
+ return len ;
54
+ }
55
+
56
+ public ListNode moveList (int difference , ListNode head ){
57
+ while (difference != 0 ){
58
+ head = head .next ;
59
+ difference --;
60
+ }
61
+ return head ;
62
+ }
63
+ }
You can’t perform that action at this time.
0 commit comments