-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack_Linked_List.js
79 lines (65 loc) · 1.33 KB
/
Stack_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
class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class Stack {
constructor(){
this.top = null;
this.bottom = null;
this.length = 0;
}
peek() {
if(this.top === null){
return undefined;
}
return this.top.value;
}
push(value){
//If the top is empty
if(this.top === null){
const new_node = new Node(value);
this.top = new_node;
this.bottom = new_node;
this.length++;
return this;
}
//If the top is not empty
const new_node = new Node(value);
new_node.next = this.top;
this.top = new_node;
this.length++;
return this;
}
pop(){
if(this.top === null){
console.log("Hello");
return undefined;
}
if(this.top === this.bottom){
this.bottom = null;
}
let remove_node = this.top;
let get_node = remove_node.next;
this.top = get_node;
this.length--;
return this;
}
isEmpty(){
return this.length === 0;
}
}
const myStack = new Stack();
console.log(myStack.isEmpty());
myStack.push('google');
myStack.push('Udemy');
console.log(myStack.push('Discord'));
console.log("Peek method: "+myStack.peek());
console.log(myStack.isEmpty());
console.log(myStack.pop());
console.log(myStack);
console.log(myStack.pop());
console.log(myStack);
console.log(myStack.pop());
console.log(myStack.isEmpty());