feat: 添加栈数据结构
This commit is contained in:
parent
89042e81a8
commit
27d3b489e3
50
stack/index.js
Normal file
50
stack/index.js
Normal file
@ -0,0 +1,50 @@
|
||||
class Stack {
|
||||
constructor(items = []) {
|
||||
this.items = items; // 用 items 来存储栈的元素
|
||||
}
|
||||
|
||||
// 入栈
|
||||
push(item) {
|
||||
this.items.push(item);
|
||||
}
|
||||
|
||||
// 出栈
|
||||
pop() {
|
||||
if (this.isEmpty()) {
|
||||
console.log('栈为空! ');
|
||||
return undefined; // 栈为空时返回 undefined
|
||||
}
|
||||
return this.items.pop();
|
||||
}
|
||||
|
||||
// 获取栈顶元素
|
||||
peek() {
|
||||
if (this.isEmpty()) {
|
||||
console.log('栈为空! ');
|
||||
return undefined; // 栈为空时返回 undefined
|
||||
}
|
||||
return this.items[this.items.length - 1];
|
||||
}
|
||||
|
||||
// 判断栈是否为空
|
||||
isEmpty() {
|
||||
return this.items.length === 0;
|
||||
}
|
||||
|
||||
// 获取栈的大小
|
||||
size() {
|
||||
return this.items.length;
|
||||
}
|
||||
|
||||
// 清空栈
|
||||
clear() {
|
||||
this.items = [];
|
||||
}
|
||||
|
||||
// 打印栈内容
|
||||
print() {
|
||||
console.log(this.items.toString());
|
||||
}
|
||||
}
|
||||
|
||||
export default Stack;
|
Loading…
x
Reference in New Issue
Block a user