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]));

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 第五章******************************************************...
    fastwe阅读 3,987评论 0 0
  • 本文目录: 1.说一说函数中的私有方法、公共方法以及静态方法 2.说一说this的指向 3.说一说call()、a...
    前端辉羽阅读 2,944评论 0 10
  • 堆的定义 堆是一种比较特殊的数据结构,可以被看做一棵树的数组对象,具有以下的性质: 堆中某个节点的值总是不大于或不...
    lucas7lw阅读 4,643评论 2 14
  • 20、有效的括号给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 有...
    BigBigFlower阅读 3,395评论 0 0
  • 1、 单线程、任务队列的概念 单线程: JavaScript是一个单线程语言,浏览器只会分配一个javascrip...
    海山城阅读 4,649评论 0 1