/*
基于链表的 - 堆栈
尾部插入和删除
*/
class LinkListStack{
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(value){
if(!this.tail) {
this.head = this.tail = {value, next: null, prev: null};
} else {
this.tail.next = {value, next: null, prev:this.tail};
this.tail = this.tail.next
}
this.length++;
}
pop() {
let value;
if(!this.tail) return undefined;
else{
const value = this.tail.value;
if(!this.tail.prev){
// 只剩最后一个了
this.tail = this.head = null;
} else {
this.tail.prev.next = null;
this.tail = this.tail.prev;
}
this.length--;
return value;
}
}
}
const list = new LinkListStack();
list.push(1);
list.push(2);
list.push(3);
console.log(list.pop());
console.log(list);
总结: