鍊錶(linked list)是由一組被稱為結點的資料元素組成的資料結構,每個結點都包含結點本身的資訊和指向下乙個結點的位址。由於每個結點都包含了可以鏈結起來的位址資訊,所以用乙個變數就能夠訪問整個結點序列。也就是說,結點包含兩部分資訊:一部分用於儲存資料元素的值,稱為資訊域;另一部分用於儲存下乙個資料元素位址的指標,稱為指標域。鍊錶中的第乙個結點的位址儲存在乙個單獨的結點中,稱為頭結點或首結點。鍊錶中的最後乙個結點沒有後繼元素,其指標域為空。
python構造的單鏈表的功能包括 頭插入,尾插入,查詢,刪除,長度。
#coding:utf8
class node():
def __init__(self,val,nt = none):
self.value = val
self.next = nt
class singnallist():
def __init__(self):
self.head = none
self.tail = none
self.size = 0
def __str__(self):
newlist = self.head
s = ''
while newlist:
s +=str(newlist.value)
if newlist.next:
s+=","
newlist = newlist.next
return s
def addhead(self,data):
newlist = node(data,none)
if self.head == none:
self.head = newlist
self.tail = newlist
else:
newlist.next = self.head
self.head = newlist
self.size += 1
def addtail(self,data):
newlist = node(data,none)
if self.head == none:
self.head = newlist
self.tail = newlist
else:
self.tail.next = newlist
self.tail = newlist
self.size += 1
def finds(self,index):
if self.size == 0:
return
if index > self.size:
return
cur = self.head
cnt = 0
while cur :
if cnt == index:
return cur.value
cnt += 1
cur = cur.next
def delets(self,data):
if self.size == 0:
return
cur = self.head
per = none
while cur:
if cur.value == data:
break
per = cur
cur = cur.next
if cur == self.head:
self.head = cur.next
else:
per.next = cur.next
self.size -= 1
def lens(self):
return self.size
if __name__== "__main__":
s = singnallist()
s.addhead(['d','3','5'])
s.addhead(2)
s.addtail(4)
s.addtail(6)
s.addhead(0)
s.addtail(9)
print s
print s.size
print s.finds(2)
s.delets(0)
s.addhead('rt')
print s
單鏈表的構造(C )
單鏈表的構造,包括最常用函式,setdata insert remove getdata search 如下 include include using namespace std templatestruct linknode linknode const t item,linknode ptr ...
python 單鏈表
class node def init self,cargo none,next none self.cargo cargo self.next next def str self return str self.cargo node1 node one node2 node two node1.n...
單鏈表 python
class node object def init self,item self.item item self.next none class singlelist object def init self self.head none def is empty self return self....