Implementation of Python Stack and Queue

Keywords: PHP Python

In python, lists can be used both as stacks and as queues.

 

Use lists as stacks

Stack: Last in, first out

stack=[1,2,3]
stack.append(4)  #On the stack, with the end of the list as the top of the stack
print(stack.pop())  #Stack 4
print(stack)  #[1, 2, 3]

 

 

Use lists as queues

Queue: First in, first out

from collections import deque
list=[1,2,3]
queue=deque(list)  #Converting lists to queues
queue.append(0)  #Enter the queue, add to the end of the queue
print(queue.popleft())  #Out, pop up and return to the head element
print(queue)  #deque([2, 3, 0])

#Using lists as queues is inefficient because all the elements behind them are moved when they are out of the queue.

 

 

deque

deque is a bilateral queue, which has the properties of stack and queue, and can perform stack and queue related operations. And on the basis of list, we add some operations such as moving, rotating, adding and deleting.

from collections import deque  #Need to import module
list=[1,2,3]
deque=deque(list)  #Convert the list to deque

deque.append(4)  #Add to the tail
print(deque)  #deque([1, 2, 3, 0])

deque.appendleft(0)  #Add to Header
print(deque)  #deque([0, 1, 2, 3, 4])

print(deque.pop())   #Pop up and return the last element 4
print(deque)  #deque([0, 1, 2, 3])

print(deque.popleft())  #Pop up and return to the first element 0 on the left
print(deque)  #deque([1, 2, 3])

 

 

deque implementation stack:

from collections import deque  #Need to import module
list=[1,2,3]
deque=deque(list)  #Convert the list to deque

#Use as a stack: Mode 1
deque.append(4)  #Push
print(deque)  #deque([1, 2, 3, 4])
print(deque.pop())  #Stack 4
print(deque)  #deque([1, 2, 3])

#Use as a stack: Mode 2
deque.appendleft(0)  #Push
print(deque)  #deque([0,1, 2, 3])
print(deque.pop())  #Stack 3
print(deque)  #deque([0, 1, 2])

#Just realize LIFO

 

 

deque implementation queue:

from collections import deque  #Need to import module
list=[1,2,3]
deque=deque(list)  #Convert the list to deque

#Use as a queue: Mode 1
deque.append(4)  #Join the team
print(deque)  #deque([1, 2, 3, 4])
print(deque.popleft())  #Team 1
print(deque)  #deque([2, 3, 4])

 

from collections import deque  #Need to import module
list=[]  #Null list
deque=deque(list)

#Use as a queue: Mode 2
deque.appendleft(1)  #Join the team
deque.appendleft(2)  
print(deque)  #deque([2, 1])
print(deque.pop())  #Team 1
print(deque)  #deque([2])

#This approach requires list It's empty.

#As long as we achieve first in first out

 

 

When implementing stacks and queues, empty lists are generally used.

Posted by neox_blueline on Sat, 05 Oct 2019 14:08:08 -0700