JavaScript实现一个栈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/michael51/article/details/88213654
function Stack() {
	this.dataStore = [];
	this.top       = 0;
	this.push      = push;
	this.pop       = pop;
	this.peek      = peek;
	this.clear     = clear;
	this.length    = length;
}

/**
 * 先来实现 push() 方法。
 * 当向栈中压入一个新元素时,需要将其保存在数组中变量 top 所对应的位置,
 * 然后将 top 值加 1,让其指向数组中下一个空位置。
 */
function push(element) {
	this.dataStore[this.top++] = element;
}

/**
 * peek() 方法返回数组的第 top-1 个位置的元素,即栈顶元素。
 * @returns {*}
 */
function peek() {
	return this.dataStore[this.top - 1];
}

/**
 * pop() 方法恰好与 push() 方法相反——它返回栈顶元素,同时将变量 top 的值减 1。
 * @returns {*}
 */
function pop() {
	return this.dataStore[--this.top];
}

function clear() {
	this.top = 0;
}

/**
 * 有时候需要知道栈内存储了多少个元素。
 * length() 方法通过返回变量 top 值的方式返回栈内的元素个数
 * @returns {*}
 */
function length() {
	return this.top;
}

//测试
var s = new Stack();
s.push("David");
s.push("Raymond");
s.push("Bryan");

console.log("length应该是3: " + s.length());
console.log('s.peek()应该输出Bryan:', s.peek());

var popped = s.pop();

console.log("The popped element is Bryan:", popped);
console.log('s.peek()应该是Raymond:', s.peek());

s.push("Cynthia");
console.log('s.peek() should be Cynthia', s.peek());

s.clear();

console.log("length should be 0: " + s.length());
console.log('s.peek()应该是undefined:', s.peek());

s.push("Clayton");
console.log('s.peek()应该是Clayton:', s.peek());

猜你喜欢

转载自blog.csdn.net/michael51/article/details/88213654
今日推荐