栈的特性:先进后出,只能在栈顶操作数据,一个栈应该有基本的操作方法:入栈,出栈,获取栈顶元素,获取栈长度,以及清空。

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
function Stack(){
this.dataStore = [];
this.top = 0;
this.push = push;
this.pop = pop;
this.peek = peek;
this.length = length;
this.clear = clear;
}

function push(ele){
this.dataStore[this.top++] = ele;
}
function pop(){
return this.dataStore[--this.top];
}
function length(){
return this.top;
}
function peek(){
return this.dataStore[this.top-1];
}
function clear(){
this.top = 0; // 直接把指针播到最低
}
function isEmpty(){
return this.top === 0?true:false;
}

应用:用栈的思想实现括号匹配

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var s = new Stack();
var str = "console.log(this.Stack())"

function judge(str){
for(var i = 0;i < str.length; i++){
if(str[i] === "("){
s.push(str[i]);
}else if(str[i] === ")"){
if(s.isEmpty()){
return false;
}
s.pop();
}
}
return s.isEmpty();
}

judge(str) // true