Praktikum_mf

Реализация стека

Mar 30th, 2021
490
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Stack {
  2.     constructor() {
  3.         this.size = 0;
  4.         this.head = null;
  5.         this.tail = null;
  6.     }
  7.  
  8.     push(value) {
  9.         const node = { value, next: null, prev: null };
  10.  
  11.         node.prev = this.tail;
  12.  
  13.         if (this.tail) {
  14.             this.tail.next = node;
  15.             this.tail = node;
  16.         } else {
  17.             this.head = this.tail = node;
  18.         }
  19.  
  20.         this.size++;
  21.     }
  22.  
  23.     pop() {
  24.         if (this.isEmpty()) {
  25.             throw new Error('Не могу удалить из пустого стека');
  26.         }
  27.  
  28.         const node = this.tail;
  29.         const prevNode = node.prev;
  30.  
  31.         if (prevNode) {
  32.             node.prev = null;
  33.             prevNode.next = null;
  34.         }
  35.  
  36.         this.tail = prevNode;
  37.  
  38.         if (this.head === node) {
  39.             this.head = prevNode;
  40.         }
  41.  
  42.         this.size--;
  43.  
  44.         return node;
  45.     }
  46.  
  47.     peek() {
  48.         return this.tail;
  49.     }
  50.  
  51.     isEmpty() {
  52.         return this.tail === null;
  53.     }
  54. }
Advertisement
Add Comment
Please, Sign In to add comment