js模擬棧操作,輸入兩個數(shù)組脱惰,一個數(shù)組作為元素入棧順序搏嗡,另一個數(shù)組為出棧順序,若出棧順序符合入棧規(guī)則返回true
// 定義一個棧
function Stack () {
this.dataStore = [];
this.top = 0;
this.pop = pop;
this.push = push;
this.peek = peek; // 獲取當前棧頂元素
this.length = length;
}
function push( element ) {
this.dataStore[this.top++] = element;
}
function pop() {
return this.dataStore[--this.top];
}
function length() {
return this.top;
}
function peek() {
if( this.top > 0 ) {
return this.dataStore[this.top-1];
}
else return 'Empty';
}
function main(pushed,poped) {
const stack = new Stack();
let popIndex=0;
pushed.forEach((item,index)=>{
stack.push(item)
while(stack.length() && stack.peek() === poped[popIndex]) {
stack.pop()
popIndex++;
}
})
return stack.top===0 ? true:false;
}
console.log(this.main([1,2,3,4,5],[4,5,3,2,1]));