javascript 堆栈_如何在原始JavaScript和ES6中实现堆栈

javascript 堆栈

by Prashant Yadav

通过Prashant Yadav

如何在原始JavaScript和ES6中实现堆栈 (How to implement a stack in vanilla JavaScript and ES6)

A stack is an ordered collection of items that follow the Last In First Out (LIFO) principle. The addition and removal of items take place at the same end, i.e. at the top. The newest elements are at the top, and the oldest elements are at the bottom.

堆栈是遵循后进先出 (LIFO)原则的项目的有序集合。 项目的添加和删除在同一末端(即顶部)进行。 最新的元素在顶部,而最旧的元素在底部。

We have many examples of stacks around us like a pile of books, a stack of trays or dishes, etc.

我们有我们身边的例子很多像一摞书,托盘或餐具等一叠

A Stack is used by compilers in programming languages, by computer memory to store variables and function calls, and in text editors to perform undo & redo operations.

编译器使用编程语言,计算机内存来存储变量和函数调用以及文本编辑器中使用堆栈来执行撤消和重做操作。

在堆栈上执行的操作列表 (List of operations performed on Stack)
  • push(): Adds a single or multiple items to the top of the Stack.

    push() :将单个或多个项目添加到堆栈的顶部。

  • pop(): Removes and Returns the top item of the Stack.

    pop() :删除并返回堆栈的顶层项目。

  • peek(): Returns the top item of the Stack.

    peek() :返回堆栈的顶层项目。

  • isEmpty(): Returns True if Stack is empty, False otherwise.

    isEmpty() :如果Stack为空,则返回True ,否则返回False

  • clear(): Removes all the items from the Stack.

    clear() :从堆栈中删除所有项目。

  • size(): Returns the length of the stack.

    size() :返回堆栈的长度。

创建堆栈 (Creating a Stack)

经典方法 (A classical approach)

We are going to implement a stack like how it is implemented in other languages apart from JavaScript.

我们将实现类似于JavaScript以外的其他语言实现的堆栈

We will use an array and an extra variable to keep track of the items.

我们将使用一个数组和一个额外的变量来跟踪项目。

function Stack(){   var items = [];   var top = 0;   //other methods go here }
将项目推入堆栈 (Push an item in the Stack)
//Push an item in the Stackthis.push = function(element){  items[top++] = element } //top++, first performs the operation then increment's the value
从堆栈中弹出一个项目 (Pop an item from the Stack)
//Pop an item from the Stackthis.pop = function(){  return items[--top]; } //--top, first decrements the value then performs the operation
从堆栈中窥视顶部物品 (Peek top item from the Stack)
//peek an item in the Stackthis.peek = function(){   return items[top - 1]; }
检查堆栈是否为空 (Check if Stack is empty)
//Is stack emptythis.isEmpty = function(){   return top === 0; }
清除堆栈 (Clear the Stack)
//clear the stackthis.clear= function(){   top = 0; }
堆栈大小 (Size of the Stack)
//Size of the Stackthis.size = function(){   return top; }
完成堆栈的实现 (Complete implementation of the Stack)
function Stack(){   var items = [];   var top = 0;   //other methods go here
//Push an item in the Stack   this.push = function(element){      items[top++] = element   } //top++, first performs the operation then increment's the value
//Pop an item from the Stack   this.pop = function(){      return items[--top];   } //--top, first decrements the value then performs the operation
//Peek top item of the Stack   this.peek = function(){      return items[top - 1];   }
//Is Stack empty   this.isEmpty = function(){     return top === 0;   }
//Clear the Stack   this.clear = function(){     top = 0;   }
//Size of the Stack   this.size = function(){      return top;   }
}
(Example)

We will now create a new instance of what we have implemented and check if it is working correctly.

现在,我们将创建一个已实现实例的新实例,并检查其是否正常运行。

var stack = new Stack(); //creating new instance of Stack stack.push(1); stack.push(2); stack.push(3); console.log(stack.peek()); console.log(stack.isEmpty()); console.log(stack.size()); console.log(stack.pop()); console.log(stack.size()); stack.clear(); console.log(stack.isEmpty());
Output: 3 false 3 3 2 true

使用JavaScript进行堆栈实施 (Stack implementation with JavaScript)

We are going to implement a stack with a JavaScript array which has inbuilt methods like push and pop.

我们将使用JavaScript 数组实现一个堆栈,该数组具有诸如pushpop之类的内置方法

function Stack(){   var items = [];   //other methods go here }
将项目推入堆栈 (Push an item in the Stack)
//push an item in the Stackthis.push = function(element){   items.push(element); }
从堆栈中弹出一个项目 (Pop an item from the Stack)
//Pop an item from the Stackthis.pop = function(){   return items.pop(); }
从堆栈中窥视顶部物品 (Peek top item from the Stack)
//Peek top item of the Stackthis.peek = function(){   return items[items.length - 1]; }
检查堆栈是否为空 (Check if Stack is empty)
//Is Stack emptythis.isEmpty = function(){    return items.length === 0; }
清除堆栈 (Clear the Stack)
//Clear the Stackthis.clear = function(){   items.length = 0; }
堆栈大小 (Size of the Stack)
//Size of the Stackthis.size = function(){   return items.length; }
完整实施Stack (Complete implementation of Stack)
function Stack(){   var items = [];   //other methods go here
//Push a item in the Stack   this.push = function(element){      items.push(element);   }
//Pop a item from the Stack   this.pop = function(){      return items.pop();   }
//Peek top item of the Stack   this.peek = function(){      return items[items.length - 1];   }
//Is Stack empty   this.isEmpty = function(){      return items.length === 0;   }
//Clear the Stack   this.clear = function(){      items.length = 0;   }
//Size of the Stack   this.size = function(){      return items.length;   }
}
通过闭包和IIFE (立即调用函数表达式)使属性和方法私有。 (Making the properties and methods private with closure and IIFE (Immediately Invoked Function Expression).)
var Stack = (function () {   return function Stack(){     var items = [];    //other methods go here
//Push an item in the Stack     this.push = function(element){        items.push(element);     }
//Pop an item from the Stack     this.pop = function(){        return items.pop();     }
//Peek top item from the Stack     this.peek = function(){        return items[items.length - 1];     }
//Is Stack empty     this.isEmpty = function(){         return items.length === 0;     }
//Clear the Stack     this.clear = function(){        items.length = 0;     }         //Size of the Stack this.size = function(){        return items.length;     }   }})();
使用ES6进行堆栈。 (Stack using ES6.)
class Stack{  constructor(){    this.items = [];  }     //other methods go here   //Push an item in the Stack   push = function(element){     this.items.push(element);   }
//Pop an item from the Stack   pop = function(){     return this.items.pop();   }        //Peek top item from the Stack   peek = function(){     return this.items[this.items.length - 1];   }
//Is Stack empty   isEmpty = function(){     return this.items.length === 0;   }
//Clear the Stack   clear = function(){      this.items.length = 0;   }        //Size of the Stack   size = function(){     return this.items.length;   }}
使用ES6 WeakMap进行堆栈。 (Stack using ES6 WeakMap.)
const items = new WeakMap();class Stack{  constructor(){    items.set(this, []);  }     //other methods go here   //Push an item in the Stack   push = function(element){     let temp = items.get(this);     temp.push(element);   }
//Pop an item from the Stack   pop = function(){     let temp = items.get(this);     return temp.pop();   }        //Peek top item from the Stack   peek = function(){     let temp = items.get(this);     return temp[temp.length - 1];   }
//Is Stack empty   isEmpty = function(){     let temp = items.get(this);     return temp.length === 0;   }
//Clear the Stack   clear = function(){      let temp = items.get(this);      temp.length = 0;   }        //Size of the Stack   size = function(){     let temp = items.get(this);     return temp.length;   }}
使用ES6 WeakMap使用闭包和IIFE(立即调用函数表达式)将属性和方法私有化(Making the properties and methods private with closure and IIFE (Immediately Invoked Function Expression) for Stack using ES6 WeakMap.)
let Stack = (() => {  const items = new WeakMap();  return class Stack{    constructor(){      items.set(this, []);    }
//other methods go here     //Push an item in the Stack     push = function(element){       let temp = items.get(this);       temp.push(element);     }
//Pop an item from the Stack     pop = function(){       let temp = items.get(this);       return temp.pop();     }
//Peek top item from the Stack     peek = function(){       let temp = items.get(this);       return temp[temp.length - 1];     }
//Is Stack empty     isEmpty = function(){       let temp = items.get(this);       return temp.length === 0;     }
//Clear the Stack     clear = function(){        let temp = items.get(this);        temp.length = 0;     }
//Size of the Stack     size = function(){       let temp = items.get(this);       return temp.length;     }  }})();
时间复杂度 (Time Complexity)

# Average

# 平均

Access: Θ(N)

出入口:Θ(N)

Search: Θ(N)

搜索:Θ(N)

Insert: Θ(1)

插入:Θ(1)

Delete: Θ(1)

删除:Θ(1)

# Worst

#最差

Access: O(N)

存取权:O(N)

Search: O(N)

搜索:O(N)

Insert: O(1)

插入:O(1)

Delete: O(1)

删除:O(1)

空间复杂度 (Space Complexity)

# Worst: O(N)

#最差 :O(N)

There are lots of problems where Stack can be the perfect data structure needed for the solution.

在很多问题中,堆栈可能是解决方案所需的理想数据结构。

If you liked this article, please give it some ?and share it! If you have any questions related to this feel free to ask me.

如果您喜欢这篇文章,请给它一些?并分享! 如果您对此有任何疑问,请随时问我。

For more like this and algorithmic solutions in Javascript, follow me on Twitter. I write about ES6, React, Nodejs, Data structures, and Algorithms on learnersbucket.com.

有关Java的更多此类信息和算法解决方案,请在 Twitter上 关注我 我写ES6 ,React过来,的NodeJS, 数据结构算法learnersbucket.com

翻译自: https://www.freecodecamp.org/news/stack-5404d9735f88/

javascript 堆栈

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值