I am solving coding challenges. Currently a doubly linked list.
The pop function is not working, it is not removing the element, and I don't understand why.
I know that I should probably implement the solution using references to the last and first element of the list. But this post is not about finding a solution to the problem but about understanding why the current approach isn't working.
export class LinkedList {
constructor() {
this.head = null
}
push(value) {
if (this.head === null) {
this.head = new Node(value, null)
return
}
var cur = this.head
while (cur.next !== null) {
cur = cur.next
}
cur.next = new Node(value, cur)
return
}
pop() {
if (this.head === null) { return null }
var cur = this.head
while (cur.next !== null) {
cur = cur.next
}
// here I am doing sth wrong, I guess.
// the thinking is that when I set the (one) reference to the last element (cur) to null,
// it should be removed from the list; why would it not be?
let value = cur.value
cur = null
return value
}
}
class Node {
constructor(value, prev) {
this.value = value;
this.next = null;
this.prev = prev;
}
}
Since the comment that helped me to figure out the problem with my approach has been deleted I want to explain here myself.
I got mixed up into thinking that by saying cur = null
I could change the value in the memory location, which would then affect all references to that location. Instead I simply changed the variable cur from holding a reference to holding the value null
.
What I should have done instead is cur.prev.next = null
.