js實現一個棧的數據結構
首先了解一下什么是棧,棧是一個后進先出的一種數據結構,執行起來效率比較高。
對於棧主要包括一些方法,彈出棧pop(),彈出棧頂元素,並刪除該元素;壓入棧push(),向棧中壓入某個方法,棧中的長度加一;讀取棧頂元素peek(),僅讀取不刪除
使用js的構造模式創建棧類,原型進行共享主要方法
代碼實現如下
(function(root) { function Stack() { this.dataStore = []; //數組的元素個數 this.top = 0; } Stack.prototype = { pop: function() { //出棧時,主要使用前減運算,返回棧頂元素,元素個數減一 return this.dataStore[--this.top]; }, push: function(elem) { //入棧時,使用后加運算符,先在棧頂添加元素,元素個數加一 this.dataStore[this.top++] = elem; }, peek: function() { return this.dataStore[this.top - 1]; }, clear: function() { //當清空棧時,訪問棧頂的結果為undefined this.top = 0; }, length: function() { return this.top; } } root.Stack = Stack; })(global); var stack = new Stack(); stack.push("liang0"); stack.push("liang1"); stack.push("liang2"); console.log(stack.peek()); console.log(stack.pop()); console.log(stack.peek()); stack.push("liang4"); console.log(stack.peek()); stack.clear(); console.log(stack.peek());