1. /*
    2. 基于链表的 - 堆栈
    3. 尾部插入和删除
    4. */
    5. class LinkListStack{
    6. constructor() {
    7. this.head = null;
    8. this.tail = null;
    9. this.length = 0;
    10. }
    11. push(value){
    12. if(!this.tail) {
    13. this.head = this.tail = {value, next: null, prev: null};
    14. } else {
    15. this.tail.next = {value, next: null, prev:this.tail};
    16. this.tail = this.tail.next
    17. }
    18. this.length++;
    19. }
    20. pop() {
    21. let value;
    22. if(!this.tail) return undefined;
    23. else{
    24. const value = this.tail.value;
    25. if(!this.tail.prev){
    26. // 只剩最后一个了
    27. this.tail = this.head = null;
    28. } else {
    29. this.tail.prev.next = null;
    30. this.tail = this.tail.prev;
    31. }
    32. this.length--;
    33. return value;
    34. }
    35. }
    36. }
    37. const list = new LinkListStack();
    38. list.push(1);
    39. list.push(2);
    40. list.push(3);
    41. console.log(list.pop());
    42. console.log(list);

    总结:
    image.png