佇列類(分別用列表和鍊錶實現)

2021-09-03 02:17:16 字數 2509 閱讀 3191

#!/usr/bin/python3

class queueunderflow(valueerror):

pass

class listqueue():  #列表實現迴圈佇列類

def __init__(self, len_=8):

self.__len = len_

self.__elems = [0] * len_ #預設每個元素都是0

self.__head = 0 #隊頭元素下標

self.__num = 0  #實際元素個數

def __len__(self):

return self.__num

def is_empty(self):

return self.__num == 0

def peek(self):

if self.__num == 0:

raise queueunderflow("元素個數為0")

return self.__elems[self.__head]

def dequeue(self):

if self.__num == 0:

raise queueunderflow("元素個數為0")

elem = self.__elems[self.__head]

self.__head = (self.__head + 1) % self.__len

self.__num = self.__num - 1

return elem

def enqueue(self, elem):

if self.__num == self.__len:

self.__extend()

self.__elems[(self.__head + self.__num) % self.__len] = elem

self.__num = self.__num + 1

def __extend(self):

old_len = self.__len

self.__len *= 2

new_elems = [0] * self.__len

for i in range(old_len):

new_elems[i] = self.__elems[(self.__head + i) % old_len]

self.__elems, self.__head = new_elems, 0

class lnode():

def __init__(self, elem, next_=none):

self.elem = elem

self.next = next_

class linkqueue(): #鍊錶實現佇列類

def __init__(self):

self.__head = none

self.__rear = none

def __len__(self):

i, p = 0, self.__head

while p:

i += 1

p = p.next

return i

def is_empty(self):

return self.__head is none #只需用__head來判斷是否為空佇列

def peek(self):

if self.__head is none:

raise queueunderflow("隊列為空")

return self.__head.elem

def dequeue(self):

if self.__head is none:

raise queueunderflow("隊列為空")

p = self.__head

self.__head = self.__head.next

return p.elem

def enqueue(self, elem):

if self.__head is none:

self.__rear = lnode(elem)

self.__head = self.__rear

else:

self.__rear.next = lnode(elem)

self.__rear = self.__rear.next

if __name__ == '__main__':

lib = "123456789"

s1 = listqueue()

s2 = linkqueue()

for i in lib:

s1.enqueue(i)

print(len(s1), len(s2))

while not s1.is_empty():

s2.enqueue(s1.peek())

print(s1.dequeue())

print(len(s1), len(s2))

while not s2.is_empty():

print(s2.dequeue())

分別用陣列和鍊錶實現堆

為了更好的理解棧的原理,本文分別用陣列和鍊錶實現了棧,關於堆和棧的區別可參考文章 1 陣列實現棧 brife 陣列實現棧類 include ifndef arraystack h define arraystack h const uint defualf stack size 3 template...

佇列(陣列實現和鍊錶實現)

1.概念 具有一定操作約束的線性表 2.特點 1 只能在一端插入 入隊 另一端刪除 出隊 2 先進先出。3.儲存實現方式 陣列 鍊錶。4.基本操作 1.陣列實現 迴圈陣列 注意 1 普通的順序儲存的陣列用來實現佇列時,存在乙個問題 當rear 記錄隊尾的變數 到達maxsize 1時,不能確定佇列是...

線性表的歸併(分別用順序儲存和鏈式儲存實現)

題目描述 已知順序線性表la和lb的元素按值非遞減排列。歸併la和lb得到新的順序線性表lc,lc的元素也按值非遞減排列。採用順序儲存形式,該程式還新增了歸併以外的幾個功能,可供使用參考。include include define ok 1 define error 0 define overfl...