Skip to content

Commit 262835d

Browse files
committed
chore: rever the linked list
1 parent 8783d15 commit 262835d

File tree

2 files changed

+108
-0
lines changed

2 files changed

+108
-0
lines changed

README.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,15 @@ The newly created node will become head of the linked list. · Size of the list
161161
We’re given the pointer/reference to the head of a singly linked list, reverse it and return the pointer/reference to the head of the reversed linked list.
162162

163163
![](https://i.imgur.com/lamsYrL.png)
164+
165+
Problem Solving steps
166+
167+
![](https://i.imgur.com/0wZ4lB1.png)
168+
169+
Running program output
170+
171+
![](https://i.imgur.com/FAHJMeF.png)
172+
164173
### Stack
165174

166175
Depth First Search (DFS) uses a `stack` for storing the nodes that it is visiting.
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { creatLinkedListFromArray } from './1-implement-linked-list.mjs';
2+
import { display } from './1-implement-linked-list.mjs';
3+
4+
/**
5+
* 2->3->4->5->6->null
6+
* R L
7+
*
8+
* 2->null
9+
*
10+
* 3->2->null
11+
* R
12+
* 4->5->6->null
13+
* L
14+
*
15+
* 4->3->2->null
16+
* R
17+
* 5->6->null
18+
* L
19+
*
20+
* 5->4->3->2->null
21+
* R
22+
* 6->null
23+
* L
24+
*
25+
* 6->5->4->3->2->null
26+
* R
27+
*
28+
*/
29+
30+
/**
31+
* 2->3->4->5->6
32+
*
33+
* R->2;
34+
* L ->3;
35+
*
36+
* R.next = null
37+
* l points next
38+
* temp = L.next
39+
L.next = R
40+
R = L
41+
L = temp
42+
43+
* L.next = R
44+
R = L
45+
*/
46+
47+
/**
48+
* runtime complexity: O(n) because reverse the list in single loop
49+
* space/memory complexity: O(1) because it is iterative
50+
* @param head head
51+
* @returns reversed head
52+
*/
53+
function reverse(head) {
54+
let reverse = head;
55+
let listToDo = head.next;
56+
57+
head.next = null;
58+
59+
while (listToDo) {
60+
let temp = listToDo.next;
61+
listToDo.next = reverse;
62+
reverse = listToDo;
63+
listToDo = temp;
64+
}
65+
66+
return reverse;
67+
}
68+
69+
const head = creatLinkedListFromArray([2, 3, 4, 5, 6]);
70+
const reversedHead = reverse(head);
71+
console.log(display(reversedHead));
72+
73+
/** TEST
74+
* 2-3-4-5-6
75+
* R L
76+
*
77+
* 2-null
78+
*
79+
* 3-2-null
80+
* R
81+
* 4-5-6-null
82+
* L
83+
*
84+
* 4-3-2-null
85+
* R
86+
* 5-6-null
87+
* L
88+
*
89+
* 5-4-3-2-null
90+
* R
91+
* 6-null
92+
* L
93+
*
94+
* 6-5-4-3-2-null
95+
* R
96+
*
97+
* null
98+
* L
99+
*/

0 commit comments

Comments
 (0)