#!/usr/bin/env python #coding = utf-8 class Node: def __init__(self,data=None,next = None): self.data = data self.next = next def rev(link): pre = link cur = link.next pre.next = None while cur: temp = cur.next cur.next = pre pre =cur cur = temp return pre if __name__ == '__main__': link = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9))))))))) root = rev(link) while root: print(root.data) 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做好了准備