-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdllPop.js
58 lines (54 loc) · 1.21 KB
/
dllPop.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
///// Coding Exercise 31: DLL pop() //////
// Implement the following on the DoublyLinkedList class - pop()
// This function should remove a node at the end of the DoublyLinkedList.
// It should return the node removed.
class Node {
constructor(val) {
this.val = val;
this.next = null;
this.prev = null;
}
}
class DoublyLinkedList {
constructor() {
this.head = null;
this.prev = null;
this.length = 0;
}
push(val) {
let newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
newNode.prev = this.tail;
this.tail = newNode;
}
this.length++;
return this;
}
pop() {
if (!this.head) return undefined;
let toBeRemoved = this.tail;
if (this.length === 1) {
this.tail = null;
this.head = null;
} else {
this.tail = toBeRemoved.prev;
this.tail.next = null;
toBeRemoved.prev = null;
}
this.length--;
return toBeRemoved;
}
}
let list = new DoublyLinkedList();
list.push("100");
list.push("200");
list.push("300");
// console.log(list);
// list.push("200");
// console.log(list);
console.log(list.pop());
console.log(list);