LeetCode - Algorithms - 160. Intersection of Two Linked Lists

Problem

160. Intersection of Two Linked Lists

Notes

  • If the two linked lists have no intersection at all, return null.
  • The linked lists must retain their original structure after the function returns.
  • Your code should preferably run in O(n) time and use only O(1) memory.

Java

my solution of O(n) time and O(1) memory

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
/**
* 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) {
if (headA == null || headB == null)
return null;
ListNode nodeA = headA;
int lenA = 0;
while (nodeA != null) {
lenA++;
nodeA = nodeA.next;
}
int lenB = 0;
ListNode nodeB = headB;
while (nodeB != null) {
lenB++;
nodeB = nodeB.next;
}
nodeA = headA;
nodeB = headB;
if (lenA < lenB) {
for (int i = 0; i < lenB - lenA; i++) {
nodeB = nodeB.next;
}
}
if (lenA > lenB) {
for (int i = 0; i < lenA - lenB; i++) {
nodeA = nodeA.next;
}
}
ListNode node = null;
if (nodeA == nodeB)
node = nodeA;
while (nodeA != nodeB) {
nodeA = nodeA.next;
nodeB = nodeB.next;
node = nodeA;
}
return node;
}
}

Submission Detail

  • 46 / 46 test cases passed.
  • Runtime: 1 ms, faster than 98.53% of Java online submissions for Intersection of Two Linked Lists.
  • Memory Usage: 41.7 MB, less than 10.90% of Java online submissions for Intersection of Two Linked Lists.

stack

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
import java.util.Deque;
import java.util.LinkedList;

/**
* 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) {
if (headA == null || headB == null)
return null;
Deque<ListNode> stkA = new LinkedList<ListNode>();
ListNode node = headA;
while (node != null) {
stkA.push(node);
node = node.next;
}
Deque<ListNode> stkB = new LinkedList<ListNode>();
node = headB;
while (node != null) {
stkB.push(node);
node = node.next;
}
while (!stkA.isEmpty() && !stkB.isEmpty()) {
if (stkA.peek() == stkB.peek()) {
node = stkA.pop();
stkB.pop();
} else
break;
}
return node;
}
}

Submission Detail

  • 46 / 46 test cases passed.
  • Runtime: 2 ms, faster than 38.55% of Java online submissions for Intersection of Two Linked Lists.
  • Memory Usage: 42.6 MB, less than 11.53% of Java online submissions for Intersection of Two Linked Lists.