Queue

# -*-coding: utf-8 -*-
# Author :writen by Qiusheng Li
# Time: 2014/08/19
# Email:[email protected]
# enqueue Insert an item at the back of the queue
# dequeue Remove an item from the front of the queue
# peek/front Retrieve an item at front of the queue without removing it
# empty/size Check whether the queue is empty or return its size
# using list impliment the Queue


#node another approach is to implement a queue as a container for nodes,as we have
#done for stacks,but now the nodes are inserted and removed in a FIFO order

class Node(object):
    def __init__(self,value=None):
        self.value = value
        self.next =None

class Queue2(object):
    '''container nodes to implement a queue class'''
    def __init__(self):
        self.first =None  # point to the first node
        self.pre = None  # point to the last node
    
    def enqueue(self,value):
        node  = Node(value)
        if self.first == None:
            self.first = node
        else:
          self.pre.next = node
        self.pre = node
        
    def dequeue(self):
        if self.first:
            value = self.first.value  # get value object is better than get node object
            self.first =  self.first.next
            return value
       # else:                         # don't use else, if contains return
            raise Exception('Queue is empty')
    def peek(self):
        if self.first:
            return self.first.value
        else:
            return None
        
    def isEmpty(self):
        return bool(self.first)
    
    def size(self):
         if self.first == None:
             return 0
         node = self.first
         i = 0
         while node:
             i += 1
             node = node.next
         return i
   
  
def Queue2Main():
    queue = Queue2()
    queue.enqueue(1)
    queue.enqueue(2)
    queue.enqueue(3)
    print "size :   ",queue.size()
    print "peek:    ",queue.peek()
    print "dequeue: ",queue.dequeue()
    print "size :   ",queue.size()
    print "peek:    ",queue.peek()
    print "dequeue: ",queue.dequeue()
    print "dequeue: ",queue.dequeue()
    print "size :   ",queue.size()               
    print "peek:    ",queue.peek()
'''testing result
size :    3
peek:     1
dequeue:  1
size :    2
peek:     2
dequeue:  2
dequeue:  3
size :    0
peek:     None
'''
if __name__ == '__main__':
    Queue2Main()

你可能感兴趣的:(Python)