스택(stack)은 제한적으로 접근할 수 있는 나열 구조이다. 그 접근 방법은 언제나 목록의 끝에서만 일어난다. 끝먼저내기 목록(Pushdown list)이라고도 한다.
스택은 한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형 구조(LIFO - Last In First Out)으로 되어 있다. 자료를 넣는 것을 '밀어넣는다' 하여 푸쉬(push)라고 하고 반대로 넣어둔 자료를 꺼내는 것을 팝(pop)이라고 하는데, 이때 꺼내지는 자료는 가장 최근에 푸쉬한 자료부터 나오게 된다.
이처럼 나중에 넣은 값이 먼저 나오는 것을 LIFO 구조라고 한다.
스택이 비었다면 0, 그렇지 않다면 1을 반환한다.
class Stack(list):
push = list.append
pop = list.pop
def is_empty(self):
if not self:
return True # stack이 비었다.
else:
return False # stack에 요소가 있다
stack = Stack()
stack.push(1)
print("stack", stack)
stack.push(2)
print("stack", stack)
stack.push(3)
print("stack", stack)
stack.pop()
# 결과
stack [1]
stack [1,2]
stack [1,2,3]
stack [1,2]
: array에서 push / pop
class Stack {
constructor() {
this.arr = [];
}
push(x) {
this.arr.push(x);
}
pop() {
return this.arr.pop();
}
empty() {
if(arr.length == 0) {
return 1;
} else {
return 0;
}
}
}
const stack = new Stack();
stack.push(1);
stack.push(2);
stack.push(3);
console.log(stack.pop()); //3
console.log('stack', stack); //[1, 2]
재귀 알고리즘을 사용하는 경우에 스택이 유용하다.