栈:
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()