python實現單鏈表的翻轉


#!/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做好了准備


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM