鍊錶的實現 輸出和反向 python

2022-08-05 18:30:17 字數 1271 閱讀 3642

鍊錶節點包含兩個元素:節點的值和指向的下乙個節點,因此可以定義鍊錶的類為:

class

linknode:

def__init__(self,value=none,next=none):

self.value=value

self.next=next

給定乙個列表l,用此列表生成乙個鍊錶時,只需按順序遍歷列表,使用遍歷到的值生成鍊錶節點,並在前後兩個節點之間建立聯絡,最後返回頭節點。

def

createlink(l):

head=linknode(l[0])

nn=head

for i in l[1:]:

nn.next=linknode(i)

nn=nn.next

return head

輸出乙個鍊錶,按順序訪問列表節點即可。

def

printlist(head):

if head==none: return

node=head

while node!=none:

print

(node.value)

node=node.next

鍊錶的反向是指對鍊錶的方向進行反轉。如給定鍊錶:1->2->3->4->5,

反向後的鍊錶為:5->4->3->2->1

反向的關鍵在於,在反向的過程中,不能丟掉了原來鍊錶節點之間的聯絡,如對前兩個節點反向時,執行2.next=1後,則對於前兩個節點,方向為2->1

但對於整個鍊錶來說,由於2.next已經被更新,鍊錶成為

就無法繼續訪問後續節點。所以,在反向的過程中,要記錄的節點有三個:前乙個節點pre,當前節點cur,下乙個節點next,這樣,在執行cur.next=pre後,還可以繼續對next進行操作,**如下。

def

reverselink(head):

if head==none: return

if head.next==none: return

head

reversehead=none

pre,cur,next=none,head,head.next

while next!=none:

cur.next=pre

pre=cur

cur=next

next=next.next

else:reversehead=cur

return reversehead

STL鍊錶反向輸出例項

給定乙個單向鍊錶,從尾到頭輸出其每個值。include include stdio.h include include using namespace std 從尾到頭輸出list 1.遞迴方法 void list reverse1 list mylist,list iterator it 傳遞引用...

自建單向鍊錶,自建鏈棧,反向輸出單向鍊錶

題目 反向輸出單向鍊錶 解題思路 反向輸出單向鍊錶方法有很多,但筆者採用自建單向鍊錶,自建鏈棧,將單向鍊錶中元素輸入棧中,再取出棧中元素,輸入到新單向鍊錶中 見下 自定義鍊錶 鏈棧節點類 public class node 自建單向鍊錶 public class linklist 插入節點 para...

鍊錶,反向鍊錶的相關操作

假設鍊錶節點的資料結構為 struct node 建立單鏈表的程式為 struct node create unsigned int n node p head for unsigned int i 1 i n i return head 問題1 鍊錶逆置 思想為 head指標不斷後移,指標反向即可...