-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.js
More file actions
89 lines (84 loc) · 1.77 KB
/
Stack.js
File metadata and controls
89 lines (84 loc) · 1.77 KB
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
class Stack{
constructor(capacity){
this.capacity = capacity || Infinity;
this.storage = {};
this.count = 0;
}
push(value){
if (this.count < this.capacity){
this.storage[this.count++] = value;
return this.count;
}
return 'Maximum Stack exceeded'
}
pop(){
if (this.count === 0){
return 'There is nothing to remove'
}
var value = this.storage[--this.count];
delete this.storage[this.count];
if (this.count < 0){
this.count = 0;
}
return value
}
peek(){
return this.storage[this.count-1]
}
count(){
return this.count
}
}
var pokemon = new Stack();
pokemon.push('charmander')
pokemon.push('squirtle')
pokemon.push('bulbasaur')
pokemon.push('pikachu')
console.log(pokemon)
/// Stack with a Linked List
class Node{
constructor(data,next = null){
this.data = data
this.next = next
}
}
class Stack {
constructor(){
this.first = null
this.last = null
this.size = 0;
}
push(data){
let node = new Node(data)
if (!this.first){
this.first = node
this.last = node
return this.size++
}
let temporary = this.first
this.first = node
this.first.next = temporary
return this.size++
}
pop(){
if (!this.first){
return null
}
if (this.first == this.last){
this.first = null;
this.last = null;
}
let temporary = this.first
this.first = this.first.next
this.size--
return temporary
}
peek(){
return this.first.data
}
}
let cool = new Stack();
cool.push(1)
cool.push(2)
console.log(cool.peek())
console.log(cool)