首页 > 代码库 > 数据结构 队列(带尾节点的单链表实现) 回顾练习

数据结构 队列(带尾节点的单链表实现) 回顾练习

带尾节点的单链表队列 入队0(1) 出队0(1)

 

 1 #!/usr/bin/env python3
 2 
 3 class QueueUnderflow(ValueError):
 4         pass
 5 
 6 class Node(object):
 7         def __init__(self, elem, next_=None):
 8                 self.elem = elem
 9                 self.next = next_
10 
11 #queue_list
12 class LQueue(object):
13         def __init__(self):
14                 self.head = None
15                 self.rear = None
16                 self.num = 0
17 
18         def is_empty(self):
19                 return self.head is None
20 
21         def count(self):
22                 return self.num
23 
24         def dequeue(self):
25                 p = self.head
26                 if not p:
27                         raise QueueUnderflow
28                 e = p.elem
29                 self.head = p.next
30                 self.num -= 1
31                 return e
32 
33         def enqueue(self, elem):
34                 p = self.head
35                 if not p:
36                         self.head = Node(elem, self.head)
37                         self.rear = self.head
38                         self.num += 1
39                         return
40                 self.rear.next = Node(elem)
41                 self.rear = self.rear.next
42                 self.num += 1
43 
44         def peek(self):
45                 p = self.head
46                 if not p:
47                         raise QueueUnderflow
48                 e = p.elem
49                 return e
50 
51         def bianli(self):
52                 p = self.head
53                 li = []
54                 while p:
55                         li.append(p.elem)
56                         p = p.next
57                 return li
58 
59 if __name__ == __main__:
60         lq = LQueue()
61         l = [1,2,3,4,5]
62         for i in l:
63                 lq.enqueue(i)
64         print(lq.bianli())
65         lq.dequeue()
66         print(lq.peek())

 

数据结构 队列(带尾节点的单链表实现) 回顾练习