Python/Python Algorithm

[python](자료구조) stack class 구현

ID_DI 2021. 8. 25. 01:01

Stack 클래스 구현

  • 중복된 값 push 불가능
  • Stack의 size 값이 default 일 경우 5로 설정
  • overflow / underflow 주의

  • 생성자
    • stack 리스트 생성
    • size 초기화
    • top SP(Stack Pointer) 초기화
  • push() pop() view() 메소드 구현
class Stack:
    def __init__(self, size = 5):
        self.stack = [] #stack 리스트 생성
        self.size = size #stack 의사이즈
        self.top = 0 #SP(Stack Pointer) stack에 저장되는 데이터의 개수

    def push(self,data):
        if data in self.stack:
            print("{} 값은 중복된 데이터입니다.".format(data))
        else:
            if self.size > self.top:
                self.stack.append(data)
                self.top += 1
                print("{} 값을 스택에 추가합니다.".format(data))
            else:
                print("overflow 발생...스택이 가득찼습니다.")
        self.view()

    def pop(self):
        if self.top <= 0:
            print("underflow 발생...스택에 값이 존재하지 않습니다.")
        else:
            print("{} 값을 pop() 했습니다.".format(self.stack[-1]))
            del self.stack[-1]
            self.top -= 1
        self.view()

    def view(self):
        print("스택에 저장된 데이터", end = "")
        if self.top <= 0:
            print("가 존재하지 않음...underflow")
        else:
            print(": ", end = "")
            for elem in self.stack:
                print(elem, end = " ")
            print()

실행

stack = Stack()
stack.view()
stack.pop()
stack.push(111)
stack.push(111)  # 중복 데이터
stack.push(888)
stack.push(333)
stack.push(999)
stack.push(777)
stack.push(555)  # overflow
print('=' * 80)
stack.view()
print('=' * 80)
stack.pop()
stack.pop()
stack.pop()
stack.pop()
stack.pop()
stack.pop()

결과

스택에 저장된 데이터가 존재하지 않음...underflow
underflow 발생...스택에 값이 존재하지 않습니다.
스택에 저장된 데이터가 존재하지 않음...underflow
111 값을 스택에 추가합니다.
스택에 저장된 데이터: 111
111 값은 중복된 데이터입니다.
스택에 저장된 데이터: 111
888 값을 스택에 추가합니다.
스택에 저장된 데이터: 111 888
333 값을 스택에 추가합니다.
스택에 저장된 데이터: 111 888 333
999 값을 스택에 추가합니다.
스택에 저장된 데이터: 111 888 333 999
777 값을 스택에 추가합니다.
스택에 저장된 데이터: 111 888 333 999 777
overflow 발생...스택이 가득찼습니다.
스택에 저장된 데이터: 111 888 333 999 777
================================================================================
스택에 저장된 데이터: 111 888 333 999 777
================================================================================
777 값을 pop() 했습니다.
스택에 저장된 데이터: 111 888 333 999
999 값을 pop() 했습니다.
스택에 저장된 데이터: 111 888 333
333 값을 pop() 했습니다.
스택에 저장된 데이터: 111 888
888 값을 pop() 했습니다.
스택에 저장된 데이터: 111
111 값을 pop() 했습니다.
스택에 저장된 데이터가 존재하지 않음...underflow
underflow 발생...스택에 값이 존재하지 않습니다.
스택에 저장된 데이터가 존재하지 않음...underflow