데이터 구조 01 스 택

2278 단어
창고.
후진 선 출 (LIFO: Last In First Out)
# -.- coding:utf-8 -.-
from __future__ import print_function


def checker(func):

    def wrapper(self, *args, **kwargs):
        if self.empty():
            return self.items
        return func(self, *args, **kwargs)

    return wrapper


class Stack(object):

    """ :   ,     """

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

    def size(self):
        """       ."""
        return len(self.items)

    def empty(self):
        """      : True ;      : False"""
        return not self.size()

    def append(self, item):
        """            ."""
        self.items.append(item)
        return self.items

    @checker
    def peek(self):
        """            ,       ."""
        return self.items[-1]

    @checker
    def get(self):
        """            ,       ."""
        return self.items.pop()

    def __iter__(self):
        """      """
        return self

    def __next__(self):
        """Python3:     for  """
        if not self.empty():
            return self.get()
        raise StopIteration

    def next(self):
        """Python2:     for  """
        return self.__next__()

    def __str__(self):
        """    print    """
        return "{}".format(self.items)


if __name__ == '__main__':
    #        .
    stack = Stack()

    #           
    stack.append('a')
    stack.append('b')
    stack.append('c')
    stack.append('d')
    stack.append('e')

    #      
    print("     : ", stack)

    #           
    print("          : ", stack.get())

    #      
    print("     : ", stack)

    #      
    for enum, i in enumerate(stack):
        print("   {}   : ".format(enum), i)

    #     
    #      :  ['a', 'b', 'c', 'd', 'e']
    #           :  e
    #      :  ['a', 'b', 'c', 'd']
    #    0   :  d
    #    1   :  c
    #    2   :  b
    #    3   :  a

좋은 웹페이지 즐겨찾기