js栈的操作

js模拟栈操作,输入两个数组,一个数组作为元素入栈顺序,另一个数组为出栈顺序,若出栈顺序符合入栈规则返回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]));

你可能感兴趣的:(js栈的操作)