Here is code for implementing a singly-linked list:
class LinkedList {
constructor(value) {
this.head = {
value: value,
next: null,
};
this.tail = this.head;
this.length = 1;
}
append(value) {
const newNode = {
value: value,
next: null,
};
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value) {
const newNode = {
value: value,
next: null,
};
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
reverse() {
if (!this.head.next) {
return this.head;
}
let first = this.head;
this.tail = this.head;
let second = first.next;
while (second) {
const temp = second.next; //third
second.next = first;
first = second;
second = temp;
}
this.head.next = null;
this.head = first;
return this.printList();
}
}
I need someone to help me understand this reverse()
function, I tried to understand it a lot of times, and I also tried with ChatGPT haha.
The reverse()
function runtime is O(n).
2
Answers
1–>2—>3—>4
first = 1–>
second = 2–>3–>
In while
1º)
temp = 3–>4
second.next = 1–>2–>
first = 2–>1–>
second = 3–>
2º)
temp = 4
second.next=2–>1–>
first = 3–>2–>1–>
second = 4
3º)
temp = null
second.next = 3–>2–>1–>
first = 4–>3–>
second = null
4º)Out while
next 1 = null
head = 4–>3–>2–>1
A linkedList is basically sequential nodes with pointers to the next one in the list. The while loop in there is essentially taking that pointer and pointing it to the previous one instead of the next one which is why we have to hold a reference to the "temp" node.
The loop holds a reference to 3 sequential nodes at a time and it is "flipping" the pointer to second one only.