Implement a queue
Title description:
1. Use an array to implement a queue, which requires the following methods
- Enqueue
- Dequeue
- View queues
首
, 尾
elements
- View queue size
2. Queue operation
- Create a new queue (named q1)
- Enqueue array ls_1 by index from small to large
- Number of elements in the output queue
- Get the first element of the team, save it in the variable q1_gettop, and observe the number of elements in the stack
- Pop the top element of the stack, save it in the variable s1_poptop, observe the number of elements
prompt
1. Queue
Introduction
- A common data structure
- FIFO-first in first out: the element inserted first comes out first
Note
- Use an array to implement the queue. After the dequeue operation, the first half of the array space is not used
2. Code completion
class MyQueue:
def __init__(self):
self.arr = []
self.front = 0
self.rear = 0
def is_empty(self):
return self.rear == self.front
def size(self):
return self.rear - self.front
def get_front(self):
if self.is_empty():
return None
else:
return self.arr[self.front]
def get_rear(self):
if self.is_empty():
return None
else:
return self.arr[self.rear-1]
def de_queue(self):
if self.rear > self.front:
self.front += 1
else:
print('队列已空')
def en_queue(self, item):
self.arr.append(item)
self.rear += 1
Queue operation
Create a new queue (named q1)
q1 = MyQueue()
q1
<__main__.MyQueue at 0x7d42408>
Enqueue array ls_1 by index from small to large
ls_1 = list(range(1,10,2))
ls_1
[1, 3, 5, 7, 9]
for i in ls_1:
q1.en_queue(i)
Number of elements in the output queue
q1.size()
5
Get the first element of the queue, save it in the variable q1_getfront, and print the number of elements in the queue
q1_getfront = q1.get_front()
print('队首元素为:{}'.format(q1_getfront))
print('队列长度为:{}'.format(q1.size()))
队首元素为:1
队列长度为:5
Get the tail element, save it in the variable q1_getrear, print the number of queue elements
q1_getrear = q1.get_rear()
print('队尾元素为:{}'.format(q1_getrear))
print('队列长度为:{}'.format(q1.size()))
队尾元素为:9
队列长度为:5
Perform the dequeue operation, print out the head index, tail index, and the number of queue elements before and after the team
print('出队前队首索引为:{},队尾索引为:{}'.format(q1.front,q1.rear))
print('*******************')
q1.de_queue()
print('出队后队首索引为:{},队尾索引为:{}'.format(q1.front,q1.rear))
print('出队之后队列元素个数为:{}'.format(q1.size()))
出队前队首索引为:0,队尾索引为:5
*******************
出队后队首索引为:1,队尾索引为:5
出队之后队列元素个数为:4