leetcode —— 206. 反轉鏈表

反轉一個單鏈表。

示例:

輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL

解法一:迭代法

按順序遍歷鏈表,對於當前節點,使用臨時變量保存其指向的下一個節點,然後將其指向的下一個節點改爲其上一個節點,其上一個節點也需要用一個變量進行保存。

### 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:
        node = None  # 當前節點的上一個節點
        cur = head  # 當前節點
        while cur:  # 如果當前節點存在
            temp = cur.next  # 用一個臨時變量保存當前節點的下一個節點
            cur.next = node  # 更新當前節點的下一個節點
            node = cur  # 用於更新上一個節點的信息
            cur = temp  # 當前節點移動到下一個節點
        return node

解法二:遞歸法,假設當前節點後面的所有節點都已經翻轉完畢,則對於當前節點需要操作兩部分:

  1. 將當前節點指向的下一個節點指向當前節點;
  2. 當前節點的下一個節點爲None;
# 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
        temp = self.reverseList(head.next)  # 當前節點後面的所有節點都已經翻轉完畢,返回翻轉鏈表的頭結點
        head.next.next = head  # 當前節點的下一個節點指向當前節點
        head.next = None  # 當前節點的下一個節點爲None 
        return temp  # 返回包括當前節點的翻轉鏈表的頭結點
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章