-
Notifications
You must be signed in to change notification settings - Fork 21
/
stack.js
64 lines (51 loc) · 1.01 KB
/
stack.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
var Node = function(value, nextNode) {
this.value = value;
this.nextNode = nextNode;
}
var Stack = function() {
this.clear();
}
Stack.prototype.push = function(value) {
this.head = new Node(value, this.head);
this.length++;
}
Stack.prototype.pop = function() {
if(this.head.nextNode === null)
return null;
var node = this.head;
this.head = this.head.nextNode;
this.length--;
return node.value;
}
Stack.prototype.peek = function() {
return this.head.value;
}
Stack.prototype.clear = function() {
this.head = new Node(null, null);
this.length = 0;
}
// Using Array
function Stack() {
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
};
function push(val) {
this.dataStore[this.top++] = val;
};
function pop() {
return this.dataStore[--this.top];
};
function peek() {
return this.dataStore[this.top-1];
};
function length() {
return this.top;
};
function clear() {
this.top = 0;
};