1 认识栈
说起栈,你想到了什么?客栈,酒店或是旅社?是不是先订房间就有房,按照先后顺序来?JavaScript中的栈与这相像,但并不完全是这样。在JavaScript中,栈是一种高效的数据结构,其数据只能通过栈顶添加或删除,所以操作快,且更容易实现。栈是一种特殊的列表,js中的列表可以参考这篇文章:点击打开链接;
如上所述,栈内的元素只能通过列表一端访问,这一端成为栈顶。栈是一种先入后出的数据结构,这就与我们开头说到的住宿的区别,你先入住,不一定最晚离开。我们先来看一张图:数据的入栈和出栈
2 对栈的操作
对栈的操作主要是将元素压入栈和弹出栈,入栈使用push()方法,出栈使用pop()方法或peek()方法;但要注意:使用pop()方法后,虽然可以访问到栈顶元素,但栈顶元素也随之被删除,而使用peek()方法则只返回栈顶,不会删除栈顶元素。清除栈里面的所有元素可以使用clear()方法,length()方法记录栈的长度,也即栈里元素的个数。再定义一个变量记录栈顶元素的位置:top。
3 栈的实现
基于上述内容,这里实现一个栈的操作,代码如下:
function Stack() { this.dataStore = []; this.top = 0; this.push = push; this.pop = pop; this.peek = peek; this.length = length; this.clear = clear; } function push(element) { this.dataStore[this.top++] = element; } function pop() { return this.dataStore[--this.top]; } function peek() { return this.dataStore[this.top - 1]; } function length(){ return this.top; } function clear() { delete this.dataStore; this.dataStore = []; return this.top = 0; } //测试 var newStack = new Stack(); newStack.push("A"); newStack.push("B"); newStack.push("C"); console.log(newStack.dataStore); console.log(newStack.length()); console.log(newStack.peek()); newStack.pop(); console.log(newStack.peek()); newStack.clear(); console.log(newStack.dataStore);
测试结果: