Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 2f60e2d

Browse files
LC#160 added optimal solution to find intersection of two linked listO(n+m) time, O(1) space
1 parent b921bc3 commit 2f60e2d

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

‎Leetcode/leetcodeTags/LinkedList/IntersectionOfTwoLinkedLists160.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,4 +39,39 @@ public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
3939

4040
return null;
4141
}
42+
43+
public ListNode getIntersectionNode2(ListNode headA, ListNode headB) {
44+
if (headA == null || headB == null)
45+
return null;
46+
47+
int lenA = getLengthOfList(headA), lenB = getLengthOfList(headB);
48+
49+
int diff = Math.abs(lenA - lenB);
50+
51+
while (lenA > lenB) {
52+
headA = headA.next;
53+
lenA--;
54+
}
55+
56+
while (lenB > lenA) {
57+
headB = headB.next;
58+
lenB--;
59+
}
60+
61+
while (headA != headB) {
62+
headA = headA.next;
63+
headB = headB.next;
64+
}
65+
66+
return headA;
67+
}
68+
69+
private int getLengthOfList(ListNode head) {
70+
int len = 0;
71+
while (head != null) {
72+
len++;
73+
head = head.next;
74+
}
75+
return len;
76+
}
4277
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /