Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

파이썬(Python)으로 스택(Stack) 자료구조 구현하기 – Push/Pop 예제

스택(Stack)은 가장 나중에 추가된 데이터가 가장 먼저 제거되는 LIFO(Last In, First Out) 방식의 대표적인 자료구조입니다. 파이썬에서 스택을 구현하려면 먼저 스택 클래스를 정의한 뒤 해당 클래스의 인스턴스를 생성하고, 요소를 추가(push)하거나 제거(pop)하는 메서드를 정의한 후, 인스턴스를 통해 이 메서드들을 호출하면 됩니다.

아래는 파이썬으로 스택을 직접 구현한 전체 예제 코드입니다.

예제 코드

class Stack_struct:
   def __init__(self):
      self.items = []

   def check_empty(self):
      return self.items == []

   def add_elements(self, my_data):
      self.items.append(my_data)

   def delete_elements(self):
      return self.items.pop()

my_instance = Stack_struct()
while True:
   print('Push <value>')
   print('Pop')
   print('Quit')
   my_input = input('What operation would you like to perform ? ').split()

   my_op = my_input[0].strip().lower()
   if my_op == 'push':
      my_instance.add_elements(int(my_input[1]))
   elif my_op == 'pop':
      if my_instance.check_empty():
         print('The stack is empty')
      else:
         print('The deleted value is : ', my_instance.delete_elements())
   elif my_op == 'Quit':
      break

실행 결과

Push <value>
Pop
Quit
What operation would you like to perform ? Push 6
Push <value>
Pop
Quit
What operation would you like to perform ? Psuh 8
Push <value>
Pop
Quit
What operation would you like to perform ? Psuh 34
Push <value>
Pop
Quit
What operation would you like to perform ? Pop
The deleted value is : 6
Push <value>
Pop
Quit

코드 설명

  • 필요한 속성을 포함하는 ‘Stack_struct’ 클래스를 생성합니다.

  • ‘__init__’ 함수는 인스턴스가 생성될 때 내부 데이터를 저장할 빈 리스트를 초기화하는 역할을 합니다.

  • ‘check_empty’ 메서드는 스택(리스트)이 비어 있는지 여부를 확인하여 True 또는 False를 반환합니다.

  • ‘add_elements’ 메서드는 리스트의 append()를 활용해 스택 맨 위에 새로운 요소를 추가합니다.

  • ‘delete_elements’ 메서드는 pop()을 사용해 스택의 맨 위 요소를 제거하고 그 값을 반환합니다.

  • ‘Stack_struct’ 클래스의 객체(my_instance)를 생성합니다.

  • 무한 루프 안에서 사용자에게 수행할 작업(push, pop, quit)을 입력받습니다.

  • 사용자의 선택에 따라 해당 연산이 수행되며, 빈 스택에서 pop을 시도하면 ‘스택이 비어 있다’는 안내 메시지를 출력해 오류를 방지합니다.

  • 각 연산의 결과가 콘솔에 출력됩니다.

참고 사항

파이썬 리스트의 append()pop() 연산은 모두 시간 복잡도 O(1)로 매우 효율적이기 때문에, 리스트를 활용한 스택 구현은 실무에서도 널리 사용됩니다. 다만 스레드 환경에서는 queue.LifoQueue를, 성능이 중요한 경우에는 collections.deque를 사용하는 것이 더 안전하고 효율적일 수 있습니다.