【基礎(chǔ)】練習(xí)冊36-Python3_定義無序列表的類

定義無順序列表的類

代碼如下:

class Node:

? ? def __init__(self,initdata):

? ? ? ? self.data = initdata

? ? ? ? self.next = None


? ? def getData(self):

? ? ? ? return self.data


? ? def getNext(self):

? ? ? ? return self.next


? ? def setData(self,newdata):

? ? ? ? self.data = newdata


? ? def setNext(self,newnext):

? ? ? ? self.next = newnext

class UnorderedList: #append,index,insert,pop

? ? def __init__(self):

? ? ? ? self.head = None

? ? def isEmpty(self): #判斷鏈表是否為空

? ? ? ? return self.head==None


? ? def add(self,item): #在鏈表頭添加節(jié)點(diǎn)

? ? ? ? temp = Node(item)

? ? ? ? temp.setNext(self.head)

? ? ? ? self.head = temp


? ? def size(self): #元素個(gè)數(shù)

? ? ? ? temp = self.head

? ? ? ? count = 0

? ? ? ? while temp:

? ? ? ? ? ? count +=1

? ? ? ? ? ? temp = temp.getNext()

? ? ? ? return count


? ? def search(self,item):#查詢

? ? ? ? temp = self.head

? ? ? ? flag = False #判斷是否存在

? ? ? ? while temp and not flag:

? ? ? ? ? ? if temp.data == item:#temp.data

? ? ? ? ? ? ? ? flag = True

? ? ? ? ? ? temp = temp.getNext() #temp.next

? ? ? ? return flag

? ? def remove(self,item):#刪除,沒有返回值

? ? ? ? current = self.head

? ? ? ? previous = None

? ? ? ? found = False

? ? ? ? while current and not found:

? ? ? ? ? ? if current.getData() == item:

? ? ? ? ? ? ? ? found = True

? ? ? ? ? ? ? ? break

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? previous = current

? ? ? ? ? ? ? ? current = current.getNext()

? ? ? ? if previous == None:

? ? ? ? ? ? self.head = current.getNext()

? ? ? ? else:

? ? ? ? ? previous.setNext(current.getNext())



list = [1,2,3,4,5,6,7]

link_list = UnorderedList()

for i in range(len(list)):

? ? link_list.add(list[i])

num = 11

print(link_list.search(num))

print(link_list.size())



運(yùn)行結(jié)果為:

False

7

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容