Programming/Algorithm
[Algorithm] 스택 (Stack)
goatlab
2023. 6. 15. 09:17
728x90
반응형
SMALL
스택 (Stack)

스택은 제한적으로 접근할 수 있는 나열 구조이다. 그 접근 방법은 언제나 목록의 끝에서만 일어난다. 끝먼저내기 목록이라고도 한다. 스택은 한 쪽 끝에서만 자료를 넣거나 뺄 수 있는 선형 구조으로 되어 있다. 스택은 후입선출 (LIFO) 방식이다.
class ListNode:
def __init__(self, value):
self.value = value
self.next = None
class Stack:
def __init__(self):
self.head = None
self.size = 0
def is_empty(self):
return self.size == 0
def push(self, value):
new_node = ListNode(value)
new_node.next = self.head
self.head = new_node
self.size += 1
def pop(self):
if self.is_empty():
raise IndexError("pop from an empty stack")
value = self.head.value
self.head = self.head.next
self.size -= 1
return value
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.push(4)
stack.push(5)
for _ in range(5):
print(stack.pop())

728x90
반응형
LIST