Python simulates examples of stack and queue functionality based on lists

  • 2020-06-23 00:52:43
  • OfStack

This article is an example of Python's list-based simulation of stack and queue capabilities. To share for your reference, specific as follows:

Previous article https: / / www ofstack. com article / 59897. htm introduces Python realization method of the stack and queue, list is used here to simulate under one simple operation of the stack and queue.

1. Queue features: first in, first out, last in, last out

List insert and pop were used to simulate team entry and team exit:


>>> l = []
>>> l.insert(0,'p1')
>>> l.insert(0,'p2')
>>> l.insert(0,'p3')
>>> l
['p3', 'p2', 'p1']
>>> l.pop()
'p1'
>>> l.pop()
'p2'
>>> l.pop()
'p3'

List append and pop were used to simulate team entry and team exit:


>>> l = []
>>> l.append('p1')
>>> l.append('p2')
>>> l.append('p3')
>>> l
['p1', 'p2', 'p3']
>>> l.pop(0)
'p1'
>>> l.pop(0)
'p2'
>>> l.pop(0)
'p3'

2. Stack features: last in, last out, first out

Use list insert and pop methods to simulate push and push:


>>> l = []
>>> l.insert(0,'a1')
>>> l.insert(0,'a2')
>>> l.insert(0,'a3')
>>> l
['a3', 'a2', 'a1']
>>> l.pop(0)
'a3'
>>> l.pop(0)
'a2'
>>> l.pop(0)
'a1'

Use list append and pop method modes to push and push:


>>> l = []
>>> l.append('a1')
>>> l.append('a2')
>>> l.append('a3')
>>> l
['a1', 'a2', 'a3']
>>> l.pop()
'a3'
>>> l.pop()
'a2'
>>> l.pop()
'a1'

For more readers interested in Python, please refer to Python Data Structure and Algorithm Tutorial, Python Encryption and Decryption Algorithm and Skills Summary, Python Coding skills Summary, Python Function Usage Skills Summary, Python String Manipulation Skills Summary and Python Introductory and Advanced Classic Tutorial.

I hope this article has been helpful in Python programming.


Related articles: