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

Appearance settings

Commit 2dc74fd

Browse filesBrowse files
author
Kohei Asai
authored
160. Intersection of Two Linked Lists (#115)
1 parent bc91ec7 commit 2dc74fd
Copy full SHA for 2dc74fd

File tree

2 files changed

+48
-0
lines changed
Filter options

2 files changed

+48
-0
lines changed
+30Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import {
2+
createSinglyLinkedListNode,
3+
getNthNode
4+
} from "../testUtilities/LinkedList";
5+
import { SinglyLinkedListNode } from "../types/LinkedList";
6+
import getIntersectionNode from "./intersectionOfTwoLinkedLists";
7+
8+
describe("160. Intersection of Two Linked Lists", () => {
9+
const TEST_CASES: [any, number[], number[], number, number][] = [
10+
[8, [4, 1, 8, 4, 5], [5, 0, 1, 8, 4, 5], 2, 3],
11+
[2, [0, 9, 1, 2, 4], [3, 2, 4], 3, 1],
12+
[0, [2, 6, 4], [1, 5], 3, 2]
13+
];
14+
15+
for (const [, valuesA, valuesB, skipA, skipB] of TEST_CASES) {
16+
const headA = createSinglyLinkedListNode(valuesA);
17+
const headB = createSinglyLinkedListNode(valuesB);
18+
let intersection: SinglyLinkedListNode<number> | null = null;
19+
20+
if (skipA < valuesA.length) {
21+
intersection = getNthNode(headA!, skipA);
22+
23+
getNthNode(headB!, skipB - 1).next = intersection;
24+
}
25+
26+
it(`returns the ${skipA}th node of "linked list A" when called with [${valuesA}], [${valuesB}], ${skipA} and ${skipB}`, () => {
27+
expect(getIntersectionNode(headA, headB)).toBe(intersection);
28+
});
29+
}
30+
});
+18Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import { SinglyLinkedListNode } from "../types/LinkedList";
2+
3+
// 160. Intersection of Two Linked Lists
4+
// https://leetcode.com/problems/intersection-of-two-linked-lists/
5+
export default function getIntersectionNode<T>(
6+
headA: SinglyLinkedListNode<T> | null,
7+
headB: SinglyLinkedListNode<T> | null
8+
): SinglyLinkedListNode<T> | null {
9+
let a = headA;
10+
let b = headB;
11+
12+
while (a !== b) {
13+
a = a ? a.next : headB;
14+
b = b ? b.next : headA;
15+
}
16+
17+
return a;
18+
}

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.