First, the characteristics of the queue:
1. FIFO
Last First
Second, class definition queue
Class
1. Instance Properties
A.first node
B.last node
When each new element comes in, it is inserted from the very back, and each element goes out from the beginning to the outside.
2. Example method
A. into the queue Enqueue
Core algorithm: Determine whether the queue is empty, if it is empty, first,last points to the newly added node node;
If it is not empty, this first points to the position of the top element of the queue, after the end of the insertion element is complete, last points backwards by 1
B. Out of queue dequeue
Core algorithms:
Parameter: None
Return value: The value of the node
When the queue is empty, return is none, the queue is not empty, the first node is logged, and then the value of the next node is assigned to first (possibly None), and finally the value of the top node is returned.
3, exercise: With the above code, complete the 67,45,34 node order into the queue, and then start from the head of the queue to access each element in the queue.
4, Exercise: The current queue, unable to determine the number of nodes in the queue, a new instance of the property Self.num, the completion of the calculation of the queue node, on the basis of the problem is the number of print queue remaining nodes.
Third, the code:
#encoding =utf-8
Class Node (object):
def __init__ (Self, Val):
Self.value = Val
Self.next = None
Class Queue (object):
def __init__ (self):
Self.first = None
Self.last = None
def enqueue (self,n):
if Self.first = = None:
NewNode = Node (n)
Self.first = NewNode
Self.last = NewNode
Else
NewNode = Node (n)
Self.last.next = NewNode
Self.last = NewNode
def dequeue (self):
if Self.first = = None:
Return None
Else
Tmpvar = Self.first.value
Self.first = Self.first.next
if Self.first = = None:
Self.last = None
Return Tmpvar
if __name__ = = ' __main__ ':
Q = Queue ()
Varlist = [67,45,34,38,96,101]
For Var in varlist:
Q.enqueue (Var)
For I in Xrange (3):
Q.dequeue ()
node = Q.first
While node! = None:
Print Node.value
node = Node.next
Python algorithm-Queue