js 實現棧的結構


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

執行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM