Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Stack {
- constructor() {
- this.size = 0;
- this.head = null;
- this.tail = null;
- }
- push(value) {
- const node = { value, next: null, prev: null };
- node.prev = this.tail;
- if (this.tail) {
- this.tail.next = node;
- this.tail = node;
- } else {
- this.head = this.tail = node;
- }
- this.size++;
- }
- pop() {
- if (this.isEmpty()) {
- throw new Error('Не могу удалить из пустого стека');
- }
- const node = this.tail;
- const prevNode = node.prev;
- if (prevNode) {
- node.prev = null;
- prevNode.next = null;
- }
- this.tail = prevNode;
- if (this.head === node) {
- this.head = prevNode;
- }
- this.size--;
- return node;
- }
- peek() {
- return this.tail;
- }
- isEmpty() {
- return this.tail === null;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment