- 栈是一种遵循==后进先出(LIFO)==原则的有序集合,新添加或待删除的元素都保存在栈的同一端,称作栈顶。另一端就叫栈底。在栈里,新元素靠近栈定,旧元素靠近栈底。
- 栈也被用在编程语言的编译器和内存中保存变量和方法调用等,也被用于浏览器记录等。
1. 基于JavaScript数组创建栈结构
- 缺点:在使用数组时,大部分的方法时间复杂度都是O(n),如果数组有更多元素,那所需的时间就会更长,另外,数组是元素的一个有序集合,为了保证元素有序,它会占用更多的空间。
class Stack {
constructor() {
this.stack = [];
}
push(elements) {
this.stack.push(elements);
}
pop() {
return this.stack.pop();
}
peek() {
return this.stack[this.stack.length - 1];
}
isEmpty() {
return this.stack.length === 0;
}
size() {
return this.stack.length;
}
toArray() {
return this.stack;
}
toString() {
return this.stack.toString();
}
}
2. 基于JavaScript对象的栈结构
class Stack {
constructor() {
this.stack = {};
this.count = 0;
}
push(element) {
this.stack[this.count] = element;
this.count++;
}
pop() {
if (this.isEmpty()) {
return undefined;
}
this.count--;
const res = this.stack[this.count];
delete this.stack[this.count];
return res;
}
peek() {
if (this.isEmpty()) {
return undefined;
}
return this.stack[this.count];
}
isEmpty() {
return this.count === 0;
}
size() {
return this.count;
}
toArray() {
return this.stack;
}
clear() {
this.stack = {};
this.count = 0;
}
toString() {
if (this.isEmpty()) {
return '';
}
let stackString = `${this.stack[0]}`;
for (let i = 1; i < this.count;i++) {
stackString = `${stackString},${this.stack[i]}`;
}
return stackString;
}
}