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 805a41c

Browse files
author
Swastikyadav
committed
Find nth node from last of the linkedList
1 parent ea3a7d5 commit 805a41c

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed

‎DsAlgo-Questions/21-nthNodefromLast.js

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
Given a linked list and integer n, return the element n spaces from the last node in the list. Do not call the 'size' method of the linked list. Assume that n will be less than the length of the list.
3+
4+
--Examples
5+
6+
const list = new List();
7+
const.insertLast('a');
8+
const.insertLast('b');
9+
const.insertLast('c');
10+
const.insertLast('d');
11+
12+
fromLast(list, 2).data; // 'b'
13+
*/
14+
15+
// -------------------------------------------
16+
17+
// Solution 1
18+
function fromLast(list, n) {
19+
let slow = list.getFirst();
20+
let fast = list.getFirst();
21+
let phase = 1;
22+
23+
while (fast.next) {
24+
if (phase === 1) {
25+
fast = list.getAt(n);
26+
27+
phase = 2;
28+
} else if (phase === 2) {
29+
slow = slow.next;
30+
fast = fast.next;
31+
}
32+
}
33+
34+
return slow;
35+
}
36+
37+
// Solution 2
38+
function fromLast2(list, n) {
39+
let slow = list.getFirst();
40+
let fast = list.getFirst();
41+
42+
while (n > 0) {
43+
fast = fast.next;
44+
n--;
45+
}
46+
47+
while (fast.next) {
48+
slow = slow.next;
49+
fast = fast.next;
50+
}
51+
52+
return slow;
53+
}
54+
55+
// -------------------------------------------
56+
57+
// Solution technique:
58+
/*
59+
- Phase 1
60+
- Both 'slow' and 'fast' pointers will be at first node.
61+
- Move 'fast' by n points, and don't move the 'slow' pointer.
62+
63+
- Phase 2
64+
- Now 'slow' pointer is n nodes behind the 'fast' pointer.
65+
- Now for each iteration move the both pointers by 1 node.
66+
- When 'fast' is at lastNode, 'slow' must be at nth node from the last.
67+
*/

0 commit comments

Comments
(0)

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