(100 days and 2 hours the next day) Use the list as a stack

1. Use the list as a stack

Stack: first in, last out.

The list method makes the list easy to use as a stack. The stack is a specific data structure. You can use the append() method to add an element to the top of the stack. You can release an element from the top of the stack by using the pop() method without specifying an index.

list=[1,2,3,4]
print(list)
list.append(5)
list.append(6)
print(list)
print(list.pop())
print(list.pop())
print(list.pop())

  

The one who went first came out last.

2. Use the list as a queue

Queue: first in first out

The first element added in the queue is taken out first; but it is not efficient to use the list for this purpose. Adding or popping elements at the end of the list is fast, but inserting or popping from the head of the list is not fast (because all other elements have to be moved one by one).

from collections import deque
queue=deque(['a','b','c','d'])
print(queue)
queue.append('e')
queue.append('f')
queue.append('g')
print(queue)
queue.popleft()
print(queue)
queue.popleft()
print(queue)
queue.popleft()
print(queue)

  

 

Guess you like

Origin blog.csdn.net/zhangxue1232/article/details/109318522