-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathImplementStack.js
52 lines (48 loc) · 965 Bytes
/
ImplementStack.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
/*
Asked by - Samsung, Microsoft, Codenation.
Implement Stack using LinkedList.
*/
class Node{
constructor(data){
this.data = data
this.next = null
}
}
class Stack{
constructor(){
this.top = null
}
push(item){
let node = new Node(item)
if(this.top){
node.next = this.top
this.top = node
}else{
this.top = node
}
}
pop(){
if(this.top){
let itemToPop = this.top
this.top = this.top.next
return itemToPop.data
}else{
console('Stack is empty!')
return false
}
}
peek(){
if(this.top) {
return this.top.data
}else{
return null
}
}
}
let stack = new Stack()
stack.push(10) // top: 10
stack.push(20) // top: 20
stack.push(30) // top: 30
stack.push(40) // top: 40
stack.pop() // top: 30
stack.peek() // 30