[Python] 자료구조 - 스택(Stack)


 

1. 스택(Stack) 구조란?

  • 스택 구조는 가장 나중에 들어간 데이터를 가장 먼저 꺼내는 구조이다.
  • 후입선출 (LIFO, FILO) 구조인 것만 알면 된다.
  • Push : 스택에 데이터를 넣는 것
  • Pop : 스택에서 데이터를 꺼내는 것

 

2. 파이썬에서 Stack 만들어보기

2.1. 재귀함수 활용

  • 재귀함수를 활용하여 스택 자료구조의 특징을 떠올리며 구현하였고, 객체(스택) 저장은 따로 하지 않았다.
def stack_recursive(mydata):
    if mydata < 1:
        print("="*30)
        print ("push 종료")
        print("="*30)
    else:
        print(f"{mydata} is pushed")
        stack_recursive(mydata - 1)
        print(f"returned : {mydata}")

 

stack_recursive(5)
5 is pushed
4 is pushed
3 is pushed
2 is pushed
1 is pushed
==============================
push 종료
==============================
returned : 1
returned : 2
returned : 3
returned : 4
returned : 5
  • 나중에 들어간 데이터가 먼저 빠져나오는 것을 볼 수 있다.

 

2.2. 파이썬의 대표적인 스택 : list의 append & pop

  • 파이썬에서는 사실 스택 구조를 따로 만들 필요 없이 list의 append와 pop를 통해 스택 구조를 선보일 수 있다.

i) 스택의 Push를 list append로 구현

for i in range(1,6):
    mylist.append(i)
    print(f"current stack is {mylist}")
current stack is [1]
current stack is [1, 2]
current stack is [1, 2, 3]
current stack is [1, 2, 3, 4]
current stack is [1, 2, 3, 4, 5]

 

ii) 스택의 Pop를 list pop로 구현

for j in range(len(mylist)):
    print(f"current output은 {mylist.pop(-1)}입니다")
    print(f"current stack is {mylist}")
    print("="*30)
current output은 5입니다
current stack is [1, 2, 3, 4]
==============================
current output은 4입니다
current stack is [1, 2, 3]
==============================
current output은 3입니다
current stack is [1, 2]
==============================
current output은 2입니다
current stack is [1]
==============================
current output은 1입니다
current stack is []
==============================

 

+ Recent posts