Python実装スタックとキュー


スタック:
# -*- coding:utf-8 -*-
class Stack(object):
    def __init__(self):
        self.__list = []
    def push(self,item):
        return self.__list.append(item)
    def pop(self):
        return self.__list.pop()
    def peek(self):
        """      """
        if self.__list:
            return self.__list[-1]
        else:
            return None
    def is_empty(self):
        """       """
        return  self.__list == []
    def size(self):
        return len(self.__list)

if __name__=="__main__":
    s=Stack()
    print(s.is_empty())
    s.push(1)
    s.push(2)
    s.push(3)
    s.push(4)
    print(s.is_empty())
    print(s.pop())
    print(s.pop())
    print(s.pop())
    print(s.pop())

# True
# False
# 4
# 3
# 2
# 1

キュー:
# -*- coding:utf-8 -*-
class Queue(object):
    """   """
    def __init__(self):
        self.__list = []
    def inquene(self,item):
        return self.__list.insert(0,item)
    def dequeue(self):
        return self.__list.pop()
    def is_empty(self):
        return self.__list == []
    def size(self):
        return len(self.__list)

class DQueue(object):
    """    """
    def __init__(self):
        self.__list = []
    def add_front(self,item):
        return self.__list.insert(0,item)
    def add_rear(self,item):
        return self.__list.append(item)
    def pop_front(self):
        return self.__list.pop(0)
    def pop_rear(self):
        return self.__list.pop( )
    def is_empty(self):
        return self.__list == []
    def size(self):
        return len(self.__list)

if __name__ == "__main__":
    q=Queue()
    q.inquene(1)
    q.inquene(2)
    q.inquene(3)
    q.inquene(4)
    q.size()
    q.is_empty()
    print(q.dequeue())
    print(q.dequeue())
    print(q.dequeue())
    print(q.dequeue())

    d=DQueue()
    d.add_front(1)
    d.add_front(2)
    d.add_rear(3)
    d.add_rear(4)
    print(d.pop_rear())
    print(d.pop_rear())
    print(d.pop_rear())
    print(d.pop_rear())

# 1
# 2
# 3
# 4
# 4
# 3
# 1
# 2