python實現 單鏈表的翻轉
阿新 • • 發佈:2019-04-01
roo nbsp none 連接斷開 int utf self. 單鏈表 鏈表
1 #!/usr/bin/env python 2 #coding = utf-8 3 class Node: 4 def __init__(self,data=None,next = None): 5 self.data = data 6 self.next = next 7 8 def rev(link): 9 pre = link 10 cur = link.next 11 pre.next = None 12 while cur: 13 temp = cur.next14 cur.next = pre 15 pre =cur 16 cur = temp 17 return pre 18 19 if __name__ == ‘__main__‘: 20 link = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9))))))))) 21 root = rev(link) 22 while root: 23 print(root.data) 24 root =root.next
解釋一下rev函數的實現過程:
line 9-11是將原鏈表的第一個節點變成了新鏈表的最後一個節點,同時將原鏈表的第二個節點保存在cur中
line13-16就是從原鏈表的第二個節點開始遍歷到最後一個節點,將所有節點翻轉一遍
以翻轉第二個節點為例
temp = cur.next是將cur的下一個節點保存在temp中,也就是第節點3,因為翻轉後,節點2的下一個節點變成了節點1,原先節點2和節點3之間的連接斷開,通過節點2就找不到節點3了,因此需要保存
cur.next = pre就是將節點2的下一個節點指向了節點1
然後pre向後移動到原先cur的位置,cur也向後移動一個節點,也就是pre = cur ,cur =temp
這種就為翻轉節點3做好了準備
python實現 單鏈表的翻轉