用Python中的列表模拟栈和队列

栈:

class Stack:
    # implementing a stack using python lists
    def __init__(self):
        self.items = []
        
    def isEmpty(self):
        return self.items == []
    
    def push(self,item):
        self.items.append(item)
        
    def pop(self):
        self.items.pop()
        
    def peek(self):
        return self.items[len(self.items)-1]
    
    def size(self):
        return len(self.items)
    

    
def main():
    s = Stack()
    for i in range(1,10):
        s.push(i)
    
    for i in range(1,10):
        print s.peek(),
        s.pop()

if __name__ == '__main__':
    main()

队列:

#! /usr/bin/env python
#coding=utf-8
import random

class Queue:
    def __init__(self):
        self.items = []
    
    def isEmpty(self):
        return self.items == []
    
    def enqueue(self,item):
        self.items.insert(0,item)
        
    def dequeue(self):
        if (self.isEmpty()):
            return 
        self.items.pop()
    
    def front(self):
        if (not self.isEmpty()):
            return self.items[len(self.items)-1]
        else:
            return 
    
    def size(self):
        return len(self.items)

def main():
    q = Queue()
    for i in range(1,20):
        j = random.randrange(1,20)
        print j,
        q.enqueue(j)
    print 
    for i in range(1,21):
        print q.front(),
        q.dequeue()

if __name__ == '__main__':
    main()

    

    原文作者:停车场模拟问题
    原文地址: https://blog.csdn.net/flyapy/article/details/37885883
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞