python 队列简单实现
1 class QueuryExcept(Exception): ... 2 3 class LinkNode: 4 def __init__(self, value: int, next = None): 5 self.value: int = value 6 self.next: LinkNode = next 7 8 def __repr__(self) -> str: 9 li = [self.value] 10 next = self.next 11 while next: 12 li.append(next.value) 13 next = next.next 14 return str(li) 15 16 17 class MyFifoQueue: 18 def __init__(self): 19 self.__size = 0 20 self.tail_node = self.root_node = LinkNode(0) 21 22 def push(self, value): 23 self.tail_node.next = LinkNode(value) 24 self.tail_node = self.tail_node.next 25 self.__size += 1 26 27 def pop(self): 28 cur_node = self.root_node.next 29 if cur_node == None: 30 # raise QueuryExcept('queue is empty') 31 return None 32 self.root_node.next = self.root_node.next.next 33 self.__size -= 1 34 ret_value = cur_node.value 35 del cur_node 36 return ret_value 37 38 @property 39 def size(self): 40 return self.__size 41 42 def __repr__(self): 43 li = [] 44 cur = self.root_node.next 45 while cur: 46 li.append(cur.value) 47 cur = cur.next 48 return str(li) 49 50 class MyLifoQueue: 51 def __init__(self): 52 self.__size = 0 53 self.tail_node = None 54 55 def push(self, value): 56 new_node = LinkNode(value) 57 new_node.next = self.tail_node 58 self.tail_node = new_node 59 self.__size += 1 60 61 def pop(self): 62 cur_node = self.tail_node 63 if cur_node == None: 64 # raise QueuryExcept('queue is empty') 65 return None 66 self.tail_node = self.tail_node.next 67 self.__size -= 1 68 ret_value = cur_node.value 69 del cur_node 70 return ret_value 71 72 @property 73 def size(self): 74 return self.__size 75 76 def __repr__(self): 77 li = [] 78 cur = self.tail_node 79 while cur: 80 li.append(cur.value) 81 cur = cur.next 82 return str(li) 83 84 def fifo_test(): 85 print('fifo_test') 86 mylist = MyFifoQueue() 87 value = 0 88 for i in range(3): 89 value = i + 1 90 mylist.push(value) 91 print(f'push value: {value}') 92 while mylist.size > 0: 93 value = mylist.pop() 94 print(f'pop value: {value}') 95 96 def lifo_test(): 97 print('lifo_test') 98 mylist = MyLifoQueue() 99 value = 0 100 for i in range(3): 101 value = i + 1 102 mylist.push(value) 103 print(f'push value: {value}') 104 while mylist.size > 0: 105 value = mylist.pop() 106 print(f'pop value: {value}') 107 108 if __name__ == '__main__': 109 fifo_test() 110 lifo_test() 111 print('main end')