python單鏈表反轉

1.迭代的方式

    def reverse(self, head):
        if head is None or head.next is None:
            return head
        cur = head
        pre = None
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre`

2.遞歸的方式(面試一般問這種)

    def reverse2(self, head):
        # base case
        if head is None or head.next is None:
            return head
        cur = self.reverse2(head.next)  # 整個過程中cur是固定不變的,一直指向鏈表的尾節點,也就是新鏈表的頭節點。然後遞歸是從下一個開始的。
        head.next.next = head  # 表示讓head的下一個指向head
        head.next = None  # 斷開之前的指向,防止循環遞歸
        return cur

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章