Stack in Linked Structures - Python

이세진·2022년 4월 3일
0

Computer Science

목록 보기
35/74

생성일: 2021년 10월 28일 오후 8:37

StackType.py

MAX_ITEMS = 10

class NodeType:
    """ Node Type """
    def __init__(self, item):
        self.info = item
        self.next = None

class StackType:
    def __init__(self):
        self.topPtr = None

    def is_full(self):
        try:
            location = NodeType("test")
            del location
            return False
        except:
            return True

    def is_empty(self):
        return self.topPtr == None

    def push(self, item):
        '''[5]'''
        if(self.is_full()):
            return "Stack is full"
        location = NodeType(item)
        location.next = self.topPtr
        self.topPtr = location

    def pop(self):
        '''[6]'''
        if(self.is_empty()):
            return "Failed to Top"
        tempPtr = self.topPtr
        self.topPtr = self.topPtr.next
        del tempPtr

    def top(self):
        if self.is_empty():
            print("Failed to Top")
        else:
            return self.topPtr.info

    def __str__(self):
        location = self.topPtr
        while location != None:
            print(location.info, end=" ")
            location = location.next

TestStack.py

import os
from StackType import *

if __name__ == '__main__':
    my_stack = StackType()
    
    for i in range(5):
        number = int(input("enter the number: "))
        my_stack.push(number)
    
    print()
    print(my_stack.is_full())
    print()
    
    while (True):
        if (my_stack.is_empty() == True):
            break
        else:
            print(my_stack.top())
            my_stack.pop()

    print()
    print(my_stack.top())
profile
나중은 결코 오지 않는다.

0개의 댓글