Python은 List가 스택으로 사용 가능하도록 구현되어 있다.
class Stack(list):
push=list.append
def peek(self):
return self[-1]
#pop은 list의 내장함수로 이미 존재한다.
s=Stack()
s.push(1) #[1]
s.push(5) #[1,5]
s.push(10) #[1,5,10]
print("popped value is:", s.pop()) #popped value is 10
print(s) #[1,5]
print("peeked value is:", s.peek()) #peeked value is 5
print(s) #[1,5]
s=[]
s.append(1) #[1]
s.append(5) #[1,5]
s.append(10) #[1,5,10]
print("popped value is:", s.pop()) #popped value is 10
print(s) #[1,5]
print("peeked value is:", s[-1]) #peeked value is 5
print(s) #[1,5]
브라우저의 이전/다음페이지
이전페이지를 담을 스택/ 다음페이지를 담을 스택
👉🏻 새로운 페이지로 이동 시에 현재페이지를 이전페이지 스택에 push
👉🏻 이전페이지로 이동 시에 현재페이지를 다음 페이지에 push, 이전페이지의 마지막 페이지를 pop
깊이 우선 탐색(DFS)
프로그래밍에서 목록 혹은 리스트에서 접근이 양쪽에서 가능한 구조로 FIFO(First-In, First-Out)가 기본원리
class Queue(list)
put=list.append
def peek(self):
return self[0]
def get(self):
return self.pop(0)
q=Queue()
q.put(1)
q.put(5)
q.put(10)
print(q) #[1,5,10]
print("removed value is:", q.get()) #removed value is: 1
print(q) #[5,10]
print("peeked value is:", q.peek()) #peeked value is: 5
print(q) #[5,10]
from queue import Queue
q=Queue()
q.put(1)
q.put(5)
q.put(10)
print(q) #[1,5,10]
print("removed value is:", q.get()) #removed value is: 1
print(q) #[5,10]
print("peeked value is:", q.peek()) #peeked value is: 5
print(q) #[5,10]
- List를 큐로 구현
q=[]
q.append(1) #큐의 put
q.append(5)
q.append(10)
print(q) #[1,5,10]
print("removed value is:", q.pop(0)) #큐의 get #removed value is: 1
print(q) #[5,10]
print("peeked value is:", q[0]) #peeked value is: 5
print(q) #[5,10]
큐를 위해 Deque라는 별도의 자료형을 사용해야 좋은 성능을 낼 수 있음
데큐를 이용해 스택, 큐 모두 구현 가능
삽입
삭제
from collections import deque
deq=deque()
deq.appendleft(10) #[10]
deq.append(0) #[10,0]
deq.appendleft(5) #[5,10,0]
deq.pop() #[5,10]
deq.popleft() #[10]