728x90
스택이란?
- 한 쪽 끝으로만 자료를 넣고 뺼 수 있는 구조
- LIFO ( Last In First Out )
스택의 연산
- push(item) : item 하나를 스택의 맨 윗 부분에 추가한다.
- pop() : 스택에서 맨 위에 있는 item을 제거한다.
- peek() : 스택의 맨 위에 있는 항목을 반환한다.
- isEmpty() : 스택이 비어 있다면 true를 반환한다.
스택의 구현
파이썬에서의 스택
이미 list[]로 구현되어있다.
push(item) -> append(item)
lst = [1, 2, 3]
lst.append(4)
print(lst)
<--- 결과 --->
[1, 2, 3, 4]
pop() -> pop()
lst = [1, 2, 3]
lst.pop()
print(lst)
<--- 결과 --->
[1, 2]
peek() -> list[-1]
lst = [1, 2, 3]
print(lst[-1])
<--- 결과 --->
3
코드로 구현한 스택
class stack: # 스택 클래스 구현
def __init__(self): # 스택의 생성
self.list = []
def push(self, item): # 삽입 구현
self.list.append(item)
def pop(self): # 삭제 구현
return self.list.pop()
def peek(self): # -1번쨰 즉 마지막 값 반환
return self.list[-1]
def isEmpty(self): # list가 비어있다면 true
return not self.list
lst = stack()
print(lst)
lst.push(1)
lst.push(2)
lst.push(3)
print(lst.list)
print(lst.pop())
print(lst.list)
print(lst.pop())
print(lst.pop())
print(lst.isEmpty())
print(lst.list)
<--- 결과 --->
<__main__.stack object at 0x104ce9e80> # 스택 생성 확인
[1, 2, 3]
3
[1, 2]
2
1
True
[]
728x90
'Computer Science > DataStructure' 카테고리의 다른 글
[자료구조] 큐(Queue) (0) | 2023.01.10 |
---|---|
[자료구조] 선형 리스트 (Linear List) (0) | 2023.01.07 |