컴퓨터 과학 Computer Science/자료 구조 Data Structure

자료 구조 - 스택Stack, 파이썬으로 구현한 스택 예제

Tap to restart 2022. 2. 7. 16:00

스택Stack이란?

스택은 한쪽 긑에만 자료를 넣거나 뺄 수 있는 선형 구조.

나중에 들어간 것이 먼저 나온다. Last In First Out, LIFO라고 하면 스택이다.

영어 단어 stack 뜻 자체가 쌓다, 더미이다. 간단히 접시가 쌓여 있는 형태를 떠올리면 된다.

접시를 쌓아 놓았을 때 위에서부터 쓰게 된다.

참조: 위키백과 스택

 

파이썬 스택 예제

아래는 파이썬으로 구현한 스택 예이다.

 

 

class Stack:
def __init__(self, limit=10):
self._stack = []
self._limit = limit
def push(self, value):
try:
if len(self._stack) < self._limit:
self._stack.append(value)
else:
raise Exception('Stack overflow')
except Exception as e:
print(e)
def top(self):
return self._stack[-1]
def pop(self):
return self._stack.pop(-1)
def empty(self):
if len(self._stack) == 0:
return 1
else:
return 0
def __str__(self):
return self._stack
if __name__ == '__main__':
stack = Stack(limit=3)
stack.push(1)
print(stack.__str__())
stack.push(2)
print(stack.__str__())
stack.push(3)
print(stack.__str__())
stack.push(4)
print(stack.__str__())
print(stack.pop())
print(stack.__str__())
'''
# Result example
[1]
[1, 2]
[1, 2, 3]
Stack overflow
[1, 2, 3]
3
[1, 2]
'''