/
stack-use-linked-list.js
91 lines (77 loc) · 1.83 KB
/
stack-use-linked-list.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
class ListNode {
constructor(val, next) {
this.val = val;
this.next = null;
}
}
/*
Approach implementation of Stack via Linked List
push(item) - As in the stack new item are added on the top,
If the head is empty then the new node will be the first element,
else we will make all the new node of the linked list to be
the first node by assigning all the old nodes to the new node.
pop() - To remove an item from the stack we can just make the head to point
the very next element.
time: every operation takes constant time
space: depends on machine, extra space to deal with links
*/
class Stack {
constructor() {
this.head = null;
this.length = 0;
}
isEmpty() {
return this.length === 0
}
// push data into the stack
// insert a new node at the beginning of Linked list
push(item) {
// create a new node
let newNode = new ListNode(item, null);
// 2 cases if list is empty
// or head is not empty
if (!this.head) {
this.head = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.length++;
}
// remove first node from the beginning of Linked list
// that's most recently added item
pop() {
if (!this.head) return null;
this.head = this.head.next;
this.length--;
return this.head.val;
}
peek() {
if (!this.head) return null;
return this.head.val;
}
// todo
// Convert the stack to an array
// toArray = function(){
// let arr = [];
// let current = head;
// while(current){
// arr.push(current.element);
// current = current.next;
// }
// return arr;
// }
clear() {
this.head = null;
this.length = 0;
}
}
const stack = new Stack();
stack.push(1)
stack.push(2);
stack.pop();
//console.log('stack via Linked List', stack)
export {
Stack,
// StackUsingLinkedList
}