資料結構與演算法 python實現順序表

2021-10-07 12:17:47 字數 1680 閱讀 8624

順序表的實現和無序表相似,只是add方法中,需要新增條件判斷的語句

# 鍊錶的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 orderedlist:

def __init__(self):

self.head = none

def add(self, item):

current = self.head

previons = none

stop = false

# 發現插入位置

while current != none and not stop:

if current.getdata() > item:

stop = true

else:

previons = current

current = current.getnext()

temp = node(item)

if previons == none: # 插入在表頭

temp.setnext(self.head)

self.head = temp

else: # 插入在表中

temp.setnext(current)

previons.setnext(temp)

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

def search(self, item):

current = self.head

found = false

stop = false

while current != none and not found and not stop:

if current.getdata() == item:

found = true

else:

if current.getdata() > item:

stop = true

else:

current = current.getnext()

return found

# 判斷鍊錶元素個數

def size(self):

current = self.head

count = 0

while current != none:

count += 1

current = current.getnext()

return count

# 判空

def isempty(self):

return self.head == none

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 實現...