[DA] Stack

LIFO(Last In First out) ๊ตฌ์กฐ, ๋Œ€ํ‘œ์ ์œผ๋กœ ์Šคํƒ ๋ฉ”๋ชจ๋ฆฌ์— ์‚ฌ์šฉ

Array, Linked List ๋กœ ํ‘œํ˜„ ๊ฐ€๋Šฅ

Array

const stack = [];

// Push
stack.push(1);

// Pop
stack.pop();

Linked List

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

class Stack {
  constructor() {
    this.top = null;
    this.size = 0;
  }

  push(value) {
    const node = new Node(value);
    node.next = this.top;
    this.top = node;
    this.size += 1;
  }

  pop() {
    const value = this.pop.value;
    this.top = this.top.next;
    this.size -= 1;
    return value;
  }

  size() {
    return this.size;
  }
}

Categories:

Updated:

Leave a comment