数据结构篇——栈

栈是一种高效的数据结构,特点是只能在栈顶进行添加或删除操作,具有后入先出的特点,任何不在栈顶的元素都无法被访问。

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
function Stack(){
this.dataStore = [];
this.top = 0; // 记录栈顶的位置
this.push = push;
this.pop = pop;
this.peek = peek;
this.clear = clear;
this.length = length;
}

function push(element){
this.dataStore[this.top++] = element;
}

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;
}

// 测试代码
let s = new Stack();
s.push('a');
s.push('b');
s.push('c');
console.log(s.length())
console.log(s.peek())
s.push('d');
console.log(s.peek());
s.clear();
console.log(s.length());
console.log(s.peek());