鍊錶(linked list),由於python是動態語言,可以直接把物件賦值給新的變數,於是在python一切皆為物件的原理上實現鍊錶的各項操作。在實現鍊錶python類的屬性和方法操作之前,先整理一些鍊錶的理論知識。
一、鍊錶的基本結構鍊錶是通過乙個個節點(node)組成的,每個節點都包含了稱為資料域(value)和指標域(next)的基本單元,它也是一種遞迴的資料結構。它能保持資料之間的邏輯順序,但儲存空間不必按照順序儲存。 鍊錶的基本元素有:節點:每個節點有兩個部分,左邊部分稱為值域,用來存放使用者資料;右邊部分稱為指標域,用來存放指向下乙個元素的指標。head:head節點永遠指向第乙個節點tail: tail永遠指向最後乙個節點none:鍊錶中最後乙個節點的指標域為none值
二、鍊錶的種類以及和動態陣列(array list)的對比
三、單向鍊錶屬性與各類操作方法**
#先定乙個node的類
class node(): #value + next
def __init__ (self, value = none, next = none):
self._value = value
self._next = next
def getvalue(self):
return self._value
def getnext(self):
return self._next
def setvalue(self,new_value):
self._value = new_value
def setnext(self,new_next):
self._next = new_next
#實現linked list及其各類操作方法
class linkedlist():
def __init__(self): #初始化鍊錶為空表
self._head = node()
self._tail = none
self._length = 0
#檢測是否為空
def isempty(self):
return self._head == none
#add在鍊錶前端新增元素:o(1)
def add(self,value):
newnode = node(value,none) #create乙個node(為了插進乙個鍊錶)
newnode.setnext(self._head)
self._head = newnode
newnode = node(value)
if self.isempty():
self._head = newnode #若為空表,將新增的元素設為第乙個元素
else:
current = self._head
while current.getnext() != none:
current = current.getnext() #遍歷鍊錶
current.setnext(newnode) #此時current為鍊錶最後的元素
#search檢索元素是否在鍊錶中
def search(self,value):
current=self._head
foundvalue = false
while current != none and not foundvalue:
if current.getvalue() == value:
foundvalue = true
else:
current=current.getnext()
return foundvalue
#index索引元素在鍊錶中的位置
def index(self,value):
current = self._head
count = 0
found = none
while current != none and not found:
count += 1
if current.getvalue()==value:
found = true
else:
current=current.getnext()
if found:
return count
else:
raise valueerror ('%s is not in linkedlist'%value)
#remove刪除鍊錶中的某項元素
def remove(self,value):
current = self._head
pre = none
while current!=none:
if current.getvalue() == value:
if not pre:
self._head = current.getnext()
else:
pre.setnext(current.getnext())
break
else:
pre = current
current = current.getnext()
#insert鍊錶中插入元素
def insert(self,pos,value):
if pos <= 1:
self.add(value)
elif pos > self.size():
else:
temp = node(value)
count = 1
pre = none
current = self._head
while count < pos:
count += 1
pre = current
current = current.getnext()
pre.setnext(temp)
temp.setnext(current)
資料結構 Python實現 之鍊錶
理解資料結構最好的方式就是用腦洞把它想象出來。一 節點 class node def init self,data none self.data data self.left none self.right none node node 5 現在請你閉眼在腦海創造一片虛無縹緲的空間,空間裡產生乙個盒...
Python資料結構之旋轉鍊錶
題目描述 給定乙個鍊錶,旋轉鍊錶,使得每個節點向右移動k個位置,其中k是乙個非負數 樣例 給出鍊錶1 2 3 4 5 null和k 2 返回4 5 1 2 3 null 首先,觀察一下這個題目要達到的目的,其實,換一種說法,可以這樣來描述 給出乙個k值,將鍊錶從倒數第k個節點處起之後的部分移動到鍊錶...
python資料結構之鍊錶(一)
感謝大神的總結,這裡僅作轉存分享。對於靜態鍊錶,個人認為要先想想下面幾點 靜態鍊錶的儲存結構是什麼?沒有指標,怎麼來模擬指標?怎麼模擬c語言中位址的概念 怎麼去模擬記憶體管理?ok,先來聊聊第1 2點,靜態鍊錶在沒有指標的語言中用陣列來實現,用一組位址連續的儲存單元來存放資料 第一次了解到這裡,我也...