JavaScript数据结构与算法(一) 栈的实现

时间:2023-03-09 09:59:17
JavaScript数据结构与算法(一) 栈的实现

TypeScript版本源码

 class Stack {
items = [];
public push(element) {
this.items.push(element);
}
public pop() {
return this.items.pop();
}
public peek() {
return this.items[this.items.length - ];
}
public isEmpty() {
return this.items.length == ;
}
public size() {
return this.items.length;
}
public clear() {
this.items = [];
}
public print() {
console.log(this.items.toString());
}
}

TypeScript版本调用

 // 使用Stack类
// 验证一下栈是否为空
let stack = new Stack();
console.log(stack.isEmpty()); // => true // 往栈添加元素
stack.push();
stack.push(); // 查看栈里添加的最后一位元素
console.log(stack.peek()); // => 8 // 再添加一个元素
stack.push();
console.log(stack.size()); // => 3
console.log(stack.isEmpty()); // => false // 再添加一个元素
stack.push(); // 下图描绘目前我们对栈的操作,以及栈的当前状态
JavaScript数据结构与算法(一) 栈的实现
// 然后,调用两次pop方法从栈里移除2个元素: stack.pop();
stack.pop();
console.log(stack.size()); // => 2
stack.print(); // => [5,8] // 下图描绘目前我们对栈的操作,以及栈的当前状态
JavaScript数据结构与算法(一) 栈的实现

JavaScript版本源码

 var Stack = (function () {
function Stack() {
this.items = [];
}
Stack.prototype.push = function (element) {
this.items.push(element);
};
Stack.prototype.pop = function () {
return this.items.pop();
};
Stack.prototype.peek = function () {
return this.items[this.items.length - ];
};
Stack.prototype.isEmpty = function () {
return this.items.length == ;
};
Stack.prototype.size = function () {
return this.items.length;
};
Stack.prototype.clear = function () {
this.items = [];
};
Stack.prototype.print = function () {
console.log(this.items.toString());
};
return Stack;
}());

相关文章