数组的方式实现栈
class Stack {
constructor() {
this.items = [];
}
push(element,...a) {
this.items.push(element,...a);
}
pop() {
return this.items.pop();
}
peek() {
return this.items[this.items.length-1];
}
isEmpty() {
return this.items.length===0;
}
clear() {
this.items = [];
}
size() {
return this.items.length;
}
}
const stack = new Stack();
console.log(stack.isEmpty());
stack.push(3,5,8);
console.log(stack);
stack.pop();
console.log('删除了栈顶元素');
console.log(`栈大小 ${stack.size()}`);
console.log(`栈顶元素 ${stack.peek()}`);
console.log(stack);
console.log('清除栈所有元素');
stack.clear();
console.log(stack);
对象的方式实现栈
class Stack {
constructor() {
this.count = 0;
this.items = {};
}
push(element,...a) {
this.items[this.count] = element;
this.count++;
for(let i=0;i<a.length;i++) {
this.items[this.count] = a[i];
this.count++;
}
}
size() {
return this.count;
}
isEmpty() {
return this.count===0;
}
pop() {
if( this.isEmpty()) {
return undefined;
}
this.count--;
const result = this.items[this.count];
delete this.items[this.count];
return result;
}
peek() {
if( this.isEmpty()) {
return undefined;
}
return this.items[this.count-1];
}
clear() {
this.count = 0;
this.items = {};
}
toString() {
if( this.isEmpty()) {
return undefined;
}
let objString = `${this.items[0]}`;
for(let i=1;i<this.count;i++) {
objString = `${objString},${this.items[i]}`;
}
return objString;
}
}
const stack = new Stack();
console.log(stack.isEmpty());
console.log(stack);
console.log('入栈3 5 8');
stack.push(3,5,8);
console.log(stack);
console.log('出栈',stack.pop());
console.log(stack.toString());
stack.clear()
console.log('清空栈',stack);