Muscardinus

Stack 구현 본문

DataStructure

Stack 구현

Muscardinus 2020. 12. 12. 21:40
728x90

Linked List Method

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

class Stack {
  constructor() {
    this.top = null;
    this.bottom = null;
    this.length = 0;
  }
  
  peek() {
    return this.top;
  }
  
  push(value) {
    const newNode = new Node(value);
    if (!this.length) {
      this.top = newNode;
      this.bottom = newNode;
    } else {
      this.top.next = newNode;
      this.top = newNode;
    }
    this.length++;
    return this;
  }
  
  pop() {
    if (!this.length) return "EMPTY STACK";
    let target = this.bottom;
    if (this.length === 1) {
      this.top = this.bottom = null;
      this.length = 0;
      return this;
    }
    while(target.next.next) {
      target = target.next;
    }
    this.top = target;
    this.top.next = null;
    this.length --;
    return this;
  }
}

 

Array Method

class Stack {
  constructor() {
    this.array = [];
  }
  
  peek() {
    return this.array[this.array.length - 1];
  }
  
  push(value) {
    this.array.push(value);
    return this.array;
  }
  
  pop() {
    this.array.pop();
    return this.array;
  }
}

 

728x90

'DataStructure' 카테고리의 다른 글

Undirected Graph 구현  (0) 2020.12.13
Binary Search Tree 구현  (0) 2020.12.13
Queue 구현  (0) 2020.12.12
Double Linked List 구현  (0) 2020.10.15
Linked List 구현  (0) 2020.10.15
Comments