본문 바로가기

Information Science Study/Python

[Python] Class로 스택 구현하기 코드

 

Class 문법을 활용해 스택(Stack) 구현하기 실습코드

기본 라이브러리 리스트로 구현한 스택
stack = []
stack.append(1)
stack.append(2) # 요소 IN
print(stack)
stack.pop() # 요소 OUT
print(stack)

 

# 실행결과
[1,2]
[1]

 

 

Class를 활용해 구현한 스택
class node:
    def __init__(self, data):
        self.data = data
        self.next = None
    
class stack:
    def __init__(self):
        self.top = None
        self.head = node("head")
    
    def push(self, data):
        new = node(data)
        if self.top == None:
            self.top = new
            self.head.next = new
        else:
            self.top.next = new
            self.top = self.top.next

    def pop(self):
        if self.head.next == None:
            print("stack is empty")
        else:
            cur = self.head
            while cur.next is not self.top:
                cur = cur.next
            self.top = cur
            self.top.next = None

    def print(self):
        if self.head.next is None:
            print("empty")
            return
        cur = self.head.next
        print("stack : ", end="")
        while cur is not None:
            print(cur.data, end=' ')
            cur=cur.next
        print()

s = stack()
s.push(1)
s.push(2)
s.print()
s.pop()
s.print()
s.pop()
s.print()
s.pop()

 

# 실행결과
stack : 1 2
stack : 1
empty
stack is empty