Leetcode第二零六題: 反轉鏈表

題目:

反轉一個單鏈表。

示例:

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階:
你可以迭代或遞歸地反轉鏈表。你能否用兩種方法解決這道題?

來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/reverse-linked-list
著作權歸領釦網絡所有。商業轉載請聯繫官方授權,非商業轉載請註明出處。

個人思路:

經典頭插法,也可以存外部容器

官方答案推薦:

迭代或遞歸

python代碼:

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def reverseList(self, head: ListNode) -> ListNode:
        #頭插法,還可以外部容器、雙指針
        # if not head or not head.next : return head
        # newHead = ListNode(-1)
        # cur = head
        # while cur:
        #     temp = cur.next
        #     cur.next = newHead.next
        #     newHead.next = cur
        #     cur = temp
        # return newHead.next
        #遞歸,注意每次遞歸返回的都是未經處理的cur,即最後一個結點
        if not head or not head.next : return head
        cur = self.reverseList(head.next)
        head.next.next = head
        head.next = None
        return cur 

反思:

這個遞歸還真挺難想的。。。

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