棧的實現

class Stack(object):
    """"棧"""
def __init__(self):
        self.__list = []

    def push(self,item):
        """新增一個新的元素item到棧頂"""
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()
    s.push(1)
    s.push(2)
    s.push(3)
    s.push(4)
    s.push(5)
    print(s.pop())
    print(s.pop())
    print(s.pop())
    print(s.pop())

D:\python3\python3.exe F:/study/code/python/.idea/stack.py
5
4
3
2
程序已結束,退出程式碼0

佇列的實現

class Queue(object):
    def __init__(self):
        self.__list = []


    def enqueue(self,item):
        """往佇列中新增一個item元素"""
self.__list.append(item)\

    def dequeue(self):
        """從佇列頭部刪除一個元素"""
return self.__list.pop(0)

    def is_empty(self):
        """判斷一個佇列是否為空"""
return self.__list == []

    def size(self):
        """返回佇列的大小"""
return len(self.__list)

if __name__ == "__main__":
    q = Queue()
    q.enqueue(1)
    q.enqueue(2)
    q.enqueue(3)
    q.enqueue(4)
    q.enqueue(5)
    q.enqueue(6)
    q.size()
    print(q.dequeue())
    print(q.dequeue())
    print(q.dequeue())
    print(q.dequeue())
    print(q.dequeue())




執行結果:

D:\python3\python3.exe F:/study/code/python/.idea/queue.py
1
2
3
4
5


程序已結束,退出程式碼0

.