데이터 구조 03 양 방향 대기 열

2911 단어
양 방향 대기 열
그것 은 Stack 과 Queue 의 모든 능력 을 포함 하 는 혼합 선형 데이터 구조 이다.
# -.- 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 Deque(object):

    """
    Deuque:     

                ,   Stack Queue     .
    """

    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

    def insert(self, item):
        self.items.insert(0, item)
        return self.items

    @checker
    def __leftpop(self):
        return self.items.pop(0)

    @checker
    def __rightpop(self):
        return self.items.pop(-1)

    def get(self):
        return self.__leftpop()

    def rightget(self):
        return self.__rightpop()

    @checker
    def peek(self):
        return self.items[0]

    @checker
    def rightpeek(self):
        return self.items[-1]

    def __iter__(self):
        return self

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

    def next(self):
        return self.__next__()

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


if __name__ == '__main__':
    deque = Deque()

    #       
    deque.append("a")
    deque.append("b")
    deque.append("c")
    deque.insert("x")
    deque.insert("y")
    deque.insert("z")

    #     
    print("      : ", deque)
    print("     (     ): ", deque.peek())
    print("      : ", deque)
    print("     (    ): ", deque.get())
    print("      : ", deque)
    print("     (     ): ", deque.rightpeek())
    print("      : ", deque)
    print("     (    ): ", deque.rightget())
    print("      : ", deque)

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

    #     
    #       :  ['z', 'y', 'x', 'a', 'b', 'c']
    #      (     ):  z
    #       :  ['z', 'y', 'x', 'a', 'b', 'c']
    #      (    ):  z
    #       :  ['y', 'x', 'a', 'b', 'c']
    #      (     ):  c
    #       :  ['y', 'x', 'a', 'b', 'c']
    #      (    ):  c
    #       :  ['y', 'x', 'a', 'b']
    #    0   :  y
    #    1   :  x
    #    2   :  a
    #    3   :  b

좋은 웹페이지 즐겨찾기