Data Structure
[자료구조] Stack
uni_i
2022. 9. 17. 17:22
1. stack 이란?

데이터(원소)를 탑 형태로 쌓는 형태의 자료구조.
LIFO(Last In First Out)이라고 하며, 가장 마지막에 들어간 원소가 가장 처음으로 나오는 구조이다.
stack의 예시는, ctrl + z(실행 취소) , 이전페이지로 가기 등이 있다.
2. stack 의 코드 구현
class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class Stack {
constructor(){
this.top = null;
this.bottom = null;
this.length = 0;
}
peek() {
// stack에 쌓인 가장 마지막 녀석을 확인하는 메소드
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;
}
this.top = this.top.next;
this.length--;
return this;
}
//isEmpty
}
const myStack = new Stack();
3. stack의 Big-0
- search - O(n)
- insert - O(1) → push 한번
- delete - O(1) → pop 한번
4. stack 특징
- 스택은 위의 사진처럼같은 구조와 크기의 자료를 정해진 방향으로만 쌓을 수 있다.
- top으로 정한 곳을 통해서만 접근할 수 있다. (삽입, 삭제)