Skip to content

Commit 2c46b7a

Browse files
intersection of two linked list
1 parent 3a62129 commit 2c46b7a

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package easy;
2+
3+
import classes.ListNode;
4+
5+
public class IntersectionofTwoLinkedLists {
6+
/**Looked at this post: https://discuss.leetcode.com/topic/5492/concise-java-solution-o-1-memory-o-n-time*/
7+
8+
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
9+
int lenA = findLen(headA), lenB = findLen(headB);
10+
while (lenA < lenB){
11+
headB = headB.next;
12+
lenB--;
13+
}
14+
15+
while (lenB < lenA){
16+
headA = headA.next;
17+
lenA--;
18+
}
19+
20+
while (headA != headB){
21+
headA = headA.next;
22+
headB = headB.next;
23+
}
24+
25+
return headA;
26+
}
27+
28+
private int findLen(ListNode head){
29+
int len = 0;
30+
while (head != null){
31+
head = head.next;
32+
len++;
33+
}
34+
return len;
35+
}
36+
37+
}

‎README.md

+1
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@
8686
|165|[Compare Version Numbers](https://leetcode.com/problems/compare-version-numbers/)|[Solution](../../blob/master/EASY/src/easy/CompareVersionNumbers.java)| O(n)|O(1) | Easy|
8787
|162|[Find Peak Element](https://leetcode.com/problems/find-peak-element/)|[Solution](../../blob/master/MEDIUM/src/medium/FindPeakElement.java) | O(1) |O(logn)/O(n) | Binary Search|
8888
|161|[One Edit Distance](https://leetcode.com/problems/one-edit-distance/)|[Solution](../../blob/master/MEDIUM/src/medium/OneEditDistance.java) | O(n) |O(1) | |
89+
|160|[Intersection of Two Linked Lists](https://leetcode.com/problems/intersection-of-two-linked-lists/)|[Solution](../../blob/master/EASY/src/easy/IntersectionofTwoLinkedLists.java)| O(m+n)|O(1) | Easy| Linked List
8990
|157|[Read N Characters Given Read4](https://leetcode.com/problems/read-n-characters-given-read4/)|[Solution](../../blob/master/EASY/src/easy/ReadNCharactersGivenRead4.java)| O(n)|O(1) | Easy|
9091
|155|[Min Stack](https://leetcode.com/problems/min-stack/)|[Solution](../../blob/master/EASY/src/easy/MinStack.java)| O(1)|O(n) | Easy| Stack
9192
|151|[Reverse Words in a String](https://leetcode.com/problems/reverse-words-in-a-string/)|[Solution](../../blob/master/MEDIUM/src/medium/ReverseWordsinaString.java)| O(n)|O(n) | Medium|

0 commit comments

Comments
 (0)