包工頭帶你通算法--js 描述 棧,隊列(一)
簡單敘述下棧 隊列
- 棧:先進後出 ,隊列:先進先出(就是這麼簡單)。個人理解, 棧就是給個數組a = [1,2,3,4] 只能進行pop(), 和push()操作, 隊列就是隻能進行shift() push()操作
- talk is cheap show me the picture(左棧 右隊列)
這是書上的棧,隊列
感覺怪怪的
都9012年了
class Stack{
constructor(){
this.data = [];
this.top = 0;
this.length = 0;
}
// 入棧
push(ele){
this.length ++;
return this.data[this.top ++] = ele;
}
// 出棧
pop(){
this.top > 0 ? this.top -- : false;
this.length > 0 ? this.length -- : false;
return this.data.pop();
}
// 清空棧
clear(){
this.top = 0;
this.length = 0;
return this.data = [];
}
// 返回棧頂元素
posTop(){
return this.data[-- this.top]; // 這裏要先減 再賦值
}
}
var st = new Stack();