[자료구조] 스택 Stack

daybyday·2021년 3월 2일
0

자료구조

목록 보기
2/2
post-thumbnail

스택 Stack

  • 후입선출(Last In First Out - LIFO) 특성을 가지는 자료구조
  • top : 스택 맨 위의 데이터. 제일 나중에 들어온 데이터.
  • push : 스택 맨 위에 데이터 삽입
  • pop : 스택 맨 위의 데이터 삭제 및 삭제한 데이터 반환
  • peek : 스택 맨 위의 데이터를 반환하는 메서드
  • stack overflow : 스택 메모리보다 데이터를 더 넣었을 때 발생하는 오류
  • stack underflow : 스택에 메모리가 비어있는데 데이터를 꺼내려고 할 때 발생하는 오류

스택 구현

let Stack = (function () {
    function Stack() {
        this.top = null; // 스택 맨 위의 데이터
        this.count = 0;
    }
    function Node(data) {
        this.data = data;
        this.next = null; // 다음 노드를 가리킴
    }

    Stack.prototype.push = function (data) {
        let node = new Node(data);
        node.next = this.top;
        this.top = node;
        return ++this.count;
    };

    Stack.prototype.pop = function () {
        if (!this.top) { // stack underflow 방지
            return false;
        }
        let data = this.top.data;
        this.top = this.top.next;
        // 예전 this.top의 메모리 정리
        this.count--;
        return data;
    }

    Stack.prototype.peek = function () {
        return this.top.data;
    };
    return Stack;
})();


let stack = new Stack();

stack.push(1);
stack.push(3);
stack.push(5);
console.log(stack.pop()); // 5
console.log(stack);
console.log(stack.peek()); // 3
console.log(stack.size()); // 2

클래스로 구현


class Stack {
    constructor() {
        this.top = null;
        this.count = 0;
    }
    node(value) {
        return {
            value,
            next: null,
        };
    }

    push(value) {
        const node = this.node(value);
        if (this.top === null) {
            this.top = node;
        } else {
            node.next = this.top;
            this.top = node;
        }
        ++this.count;
    }

    pop() {
        if (this.count === 0) return;

        let popped;
        if (this.top && this.top.next) {
            popped = this.top;
            this.top = this.top.next;
        } else {
            popped = this.top;
            this.top = null;
        }
        this.count--;

        return popped.value;
    }

    peek() {
        return this.top.value;
    }

    size() {
        return this.count;
    }
}

let stack = new Stack();

stack.push(1);
stack.push(3);
stack.push(5);
console.log(stack.pop()); // 5
console.log(stack);
console.log(stack.peek()); // 3
console.log(stack.size()); // 2

console.log(stack);의 결과


참조

자료구조(스택, stack)
[자료구조] 자바스크립트로 스택과 큐 구현하기 (Stack & Queue)

0개의 댓글