You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
+
functionfromLast(list,n){
19
+
letslow=list.getFirst();
20
+
letfast=list.getFirst();
21
+
letphase=1;
22
+
23
+
while(fast.next){
24
+
if(phase===1){
25
+
fast=list.getAt(n);
26
+
27
+
phase=2;
28
+
}elseif(phase===2){
29
+
slow=slow.next;
30
+
fast=fast.next;
31
+
}
32
+
}
33
+
34
+
returnslow;
35
+
}
36
+
37
+
// Solution 2
38
+
functionfromLast2(list,n){
39
+
letslow=list.getFirst();
40
+
letfast=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
+
returnslow;
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.
0 commit comments