python實現單鏈表的反轉

# coding=utf-8
class Node:
    def __init__(self, data=None, next=None):
        self.data = data
        self.next = next


def Reserver(link):
    pre = link
    cur = link.next
    pre.next = None
    while cur:
        tmp = cur.next
        cur.next = pre
        pre = cur
        cur = tmp
    return pre


if __name__ == "__main__":
    node = Node(1, Node(2, Node(3, Node(4, Node(5, Node(6, Node(7, Node(8, Node(9)))))))))
    root = Reserver(node)

    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作好了準備
相關文章
相關標籤/搜索