Python無序鍊錶 類的宣告

2022-06-01 21:06:11 字數 2573 閱讀 3220

class node:  # 這裡不用加括號,具體引數都在init函式裡,這也是和函式區別的一部分,函式的公升級和高階有序集合

def __init__(self, val):

self.data = val

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 unorderlist:  # 只儲存表頭的資訊

def __init__(self):

self.head = none # 注意這裡是大寫

def isempty(self):

return self.head == none

def add(self, item): # 由於是從首向尾遍歷,那麼自然是向首新增元素方便

newnode = node(item)

newnode.setnext(self.head)

self.head = newnode

def size(self):

count = 0

p = self.head

while p != none:

count = count + 1

p = p.getnext()

return count

def search(self, content):

p = self.head

found = false # 大寫!!有了found這個較為特殊的變數時,**更加易讀清晰

while p != none and not found:

if p.getdata == content:

found = true

else:

p = p.getnext()

return found

def remove(self, content):

previous = none

current = self.head

found = false

while current != none and not found:

if current.getdata() == content:

found = true

else:

previous = current

current = current.getnext()

if found:

if previous == none:

self.head = self.head.getnext()

else:

previous.setnext(current.getnext())

newnode = node(content)

current = self.head

previous = none

while current != none:

previous = current

current = current.getnext()

if previous != none:

previous.setnext(newnode) # 注意這是函式而不是引數不能用等於,而且修改物件(這裡是node)的引數也只能通過方法

else:

current.head = newnode # 一定要區分上面的的if

def pop(self): # 刪掉鏈尾的元素

current = self.head

if current.getnext == none:

print("error: list is empty!")

else:

previous = none

while current.getnext():

previous = current

current = current.getnext()

previous.setnext(none)

def printlist(self):

p = self.head

while p:

print(p.data)

p = p.getnext()

mylist = unorderlist()

mylist.add(1)

mylist.add(2)

mylist.add(3)

mylist.add(4)

mylist.pop()

mylist.remove(3)

print("search answer is ", mylist.search(3))

print("mylist's size is %d" % mylist.size())

mylist.printlist()

Python有序鍊錶 類的宣告

class node 這裡不用加括號,具體引數都在init函式裡,這也是和函式區別的一部分,函式的公升級和高階有序集合 def init self,val self.data val self.next none def getdata self return self.data def getne...

python 實現無序鍊錶

一 鍊錶的概念 二 python實現 1 定義乙個node類 class node object def init self,val self.data val self.next none def get data self return self.data def set data self,v...

無序鍊錶的順序查詢

include include 無序鍊錶的順序查詢 1 使用鍊錶資料結構將字典對進行儲存 2 key值不能重複 3 新插入資料時,如果出現key值重複,則當前字典中該key鍵的值替換 為最新插入的值 4 對應的key鍵在字典中沒有找到時,返回查詢值為 1 typedef struct node no...