棧的實現

實現簡單,不多解釋了,使用數組來保存數據

function Stack () {
	var items = [];

	//入棧
	this.push = function (item) {
		items.push(item);
	}

	// 出棧
	this.pop = function () {
		return items.pop();
	}

	// 返回棧頂的元素
	this.peek = function () {
		return items[items.length - 1];
	}

	// 判斷棧是否爲空
	this.isEmpty = function () {
		return items.length == 0
	}

	// 清棧
	this.clear = function () {
		items = [];
	}

	// 棧的大小
	this.size = function () {
		return items.length
	}

	// 打印棧的內容
	this.print = function () {
		console.log(items);
	}
}




發佈了88 篇原創文章 · 獲贊 37 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章