Skip to content

Commit 9cf6cfb

Browse files
committed
feat: queue
1 parent c7075f5 commit 9cf6cfb

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Python_queue_by_link.py

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# 使用我们的链表作为底层的数据结构实现队列
2+
# from multiprocessing import Queue
3+
4+
class Queue_Node(object):
5+
def __init__(self, val, back = None):
6+
self.val = val
7+
self.back = back # 记录的是入队的节点指针
8+
9+
class Queue(object):
10+
# 构造函数
11+
def __init__(self):
12+
self.__head = self.__end = Queue_Node(None)
13+
14+
# 开始我们的入队操作
15+
def push(self, data):
16+
self.__head.back = Queue_Node(data)
17+
# 然后将我们的头节点执行现在新加的节点,实现节点的后移
18+
self.__head = self.__head.back
19+
20+
# 出队的操作实现
21+
def pop(self):
22+
# 实现的是先进先出
23+
# 我们这里的 end 节点是一直不用更新的,一直指向的是最初的头节点
24+
if self.__head == self.__end:
25+
raise Exception("queue is empty")
26+
self.__end = self.__end.back
27+
return self.__end.val
28+
29+
def show_front_val(self):
30+
if self.__head.back is None:
31+
raise Exception("queue is empty")
32+
return self.__head.back.val
33+
34+
def show_end_val(self):
35+
if self.__end:
36+
return self.__end.val
37+
raise Exception("queue is empty")
38+
39+
40+
if __name__ == "__main__":
41+
queue = Queue()
42+
43+
print(queue.show_end_val())
44+
queue.push(1)
45+
# print(queue.show_end_val())
46+
queue.push(2)
47+
print(queue.show_end_val())
48+
queue.push(3)
49+
print(queue.show_end_val())
50+
queue.push(4)
51+
print(queue.show_end_val())
52+
53+
# 开始出栈
54+
print(queue.show_end_val())
55+
print(queue.pop())
56+
print(queue.show_end_val())
57+
print(queue.pop())
58+
print(queue.show_end_val())
59+
print(queue.pop())
60+
print(queue.pop())
61+
62+
63+
# https://developer.aliyun.com/article/953777 队列的实现场景,消息队列的实现

0 commit comments

Comments
 (0)