Stacks

myung hun kang·2022년 11월 5일
0

둘다 linear data structure 다 여기서는 stack을 알아보겠다.

Stacks

접시를 쌓는 것과 같이 data를 쌓는다.

LIFO (Last In First Out)

쌓는 순서 반대로 데이터르 꺼내는 방식

  • 많은 프로그래밍 언어가 stack의 구조로 짜여있다.
  • browser History, Undo, redo, 페이지 뒤로가기, 앞으로 가기 등이 다 stack에서 온 기능이다.
  • Array 나 Linked List 둘다로 구현 가능하고 성능에 차이가 없다.

시간 복잡도

lookup => O(n)
pop, push, peek => O(1)

Linked list 로 stack 만들기

class Node {
  constructor(value){
    this.value = value;
    this.next = null;
  }
}
// 기본 stack 구조
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 === 0) {
      this.top = newNode;
      this.bottom = newNode;
    } else {
      const holdingPointer = this.top;
      this.top = newNode;
      this.top.next = holdingPointer;
    }
    this.length++;
    return this;
  }
  pop(){
    if (!this.top) {
      return null;
    }
    if (this.top === this.bottom) {
      this.bottom = null;
    }
    const holdingPointer = this.top;
    this.top = this.top.next;
    this.length--;
    return this;
  }
}

Array 로 stack 만들기

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

참고
Udemy " Master the Coding Interview: Data Structures + Algorithms " - Zero To Mastery

profile
프론트엔드 개발자입니다.

0개의 댓글