資料結構與演算法 python實現無序表(單鏈表)

2021-10-07 12:13:37 字數 1606 閱讀 9052

python沒有指標所以需要自己定義結點,在結點中定義資料域和指標域

# 單鏈表的python實現

# 定義乙個結點

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:

# 定義乙個頭結點,初始指向為空

def __init__(self):

self.head = none

# 向鍊錶加入元素

def add(self, item):

temp = node(item)

temp.setnext(self.head)

self.head = temp

# 判斷鍊錶元素個數

def size(self):

current = self.head

count = 0

while current != none:

count += 1

current = current.getnext()

return count

# 搜尋鍊錶,查詢元素item,找到返回true,失敗返回false

def search(self, item):

current = self.head

found = false

while current != none and not found:

if current.getdata() == item:

found = true

else:

current = current.getnext()

return found

# 刪除鍊錶元素,先查詢,找到後指向目標元素下乙個元素

# 若刪除第乙個元素直接將head指向第二個元素即可

def remove(self, item):

current = self.head

previous = none

found = false

while not found:

if current.getdata() == item:

found = true

else:

previous = current

current = current.getnext()

if previous == none:

self.head = current.getnext()

else:

previous.setnext(current.getnext())

python資料結構與演算法

coding utf 8 import sys 使用以下語句將引數的str格式轉換為int格式 l list map int sys.argv 1 split target int sys.argv 2 def binarysearch print l print target left 0 rig...

資料結構與演算法 python

元類 基礎 冒泡 它重複地走訪要排序的數列,一次比較兩個元素,如果他們的順序錯誤就把他們交換過來。走訪數列的工作是重複地進行直到沒有再需要交換,也就是說該數列已經排序完成。這個演算法的名字由來是因為越小的元素會經由交換慢慢 浮 到數列的頂端,故名氣泡排序。def bubble sort alist ...

python演算法與資料結構

若n1 n2 n3 1000,且n1平方 n2平方 n3平方 n1,n2,n3為自然數 求出所有n1 n2 n3可能的組合?n1 0 n2 0 n3 0 判斷n1 n2 n3是否等於1000,之後變n3 1,n3 2,n3 3,然後再變n2 那如果變為 n1 n2 n3 2000 了呢?思路1 實現...