Python stacks, queues of realization

In python, the list may be used as a stack, but also as a queue to use.

 

Use the list as a stack

Stack: LIFO

= Stack [l, 2,3 ] 
stack.append ( . 4)   # stack, the stack is a list tail 
Print (stack.pop ())   # popped. 4 
Print (Stack)   # [. 1, 2,. 3]

 

 

Use the list as a queue

Queue: FIFO

from Collections Import the deque 
List = [l, 2,3 ] 
Queue = the deque (List)   # list convert queue 
queue.append (0)   # enqueued added to the tail of the queue 
Print (queue.popleft ())   # dequeue , and return to the pop-up head of the queue elements 
Print (queue)   # the deque ([2,. 3, 0]) 

# the queue as a list, it is not efficient, because all the elements to move back when the team.

 

 

and

deque bilateral queue, while having properties stacks and queues can be a stack, queue related operations. And also it increases the moving, rotating, deletions and other operations based on the list.

from Collections Import the deque   # need to import module 
List = [l, 2,3 ] 
the deque = the deque (List)   # the list into the deque 

deque.append ( . 4)   # appended to the end 
Print (the deque)   # the deque ([. 1, 2 ,. 3, 0]) 

deque.appendleft (0)   # added to the header 
Print (the deque)   # the deque ([0,. 1, 2,. 3,. 4]) 

Print (deque.pop ())    # eject and return the last element . 4 
Print (the deque)   # the deque ([0,. 1, 2,. 3]) 

Print (deque.popleft ())   # eject and return the first element on the left 0 
Print(and)   # and ([1, 2, 3])

 

 

deque realized stack:

from Collections Import the deque   # need to import module 
List = [l, 2,3 ] 
the deque = the deque (List)   # the list into the deque 

# as a stack used: a manner 
deque.append (. 4)   # stack 
Print (the deque)   # the deque ([. 1, 2,. 3,. 4]) 
Print (deque.pop ())   # popped. 4 
Print (the deque)   # the deque ([. 1, 2,. 3]) 

# as a stack used: two way 
deque.appendleft ( 0)   # stack 
Print (the deque)   # the deque ([0,1, 2, 3]) 
Print (deque.pop ())   # pop 3
Print (the deque)   # the deque ([0,. 1, 2]) 

# long to achieve LIFO

 

 

deque queue:

from Collections Import the deque   # need to import module 
List = [l, 2,3 ] 
the deque = the deque (List)   # the list into the deque 

# queue as used: a manner 
deque.append (. 4)   # enqueue 
Print (the deque)   # the deque ([. 1, 2,. 3,. 4]) 
Print (deque.popleft ())   # dequeued. 1 
Print (the deque)   # the deque ([2,. 3,. 4])

 

from Collections Import the deque   # need to import module 
List = []   # empty list 
the deque = the deque (List) 

# queue as used: two way 
deque.appendleft (. 1)   # enqueue 
deque.appendleft (2 )  
 Print (the deque)   # the deque ( [2,. 1]) 
Print (deque.pop ())   # dequeued. 1 
Print (the deque)   # the deque ([2]) 

# this requires that the list is empty 

# just to achieve FIFO

 

 

Implemented stack, queue, is generally empty list [].

 

Guess you like

Origin www.cnblogs.com/chy18883701161/p/11296906.html
Recommended