【LeetCode題解】206_反轉連結串列(Reverse-Linked-List)
阿新 • • 發佈:2018-11-23
更多 LeetCode 題解筆記可以訪問我的 github。
文章目錄
描述
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
進階
你可以迭代或遞迴地反轉連結串列。你能否用兩種方法解決這道題?
解法一:迭代
思路
遍歷連結串列的每個節點,將每個節點的 next
指標指向它的前一個節點(即前驅)。因為這是一個單向連結串列,並不存在指向前一個節點的引用,因此需要一個變數儲存指向前一個節點的引用。同時,在改變節點的 next
指標之前,還需要另一個變數儲存指向下一個節點的引用。
Java 實現
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode cur = head;
while (cur != null) {
ListNode nextNode = cur.next;
cur.next = prev;
prev = cur;
cur = nextNode;
}
return prev;
}
}
Python 實現
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
prev, curr = None, head
while curr:
curr.next, prev, curr = prev, curr, curr.next
return prev
複雜度分析
- 時間複雜度: ,其中 表示連結串列的節點數
- 空間複雜度:
解法二:遞迴
思路
遞迴的思路和迭代的方式相反,遞迴是從連結串列的尾節點(tail)開始逐一改變節點的 next
指標。因此,遞迴的方式首先會遞迴到連結串列的尾節點,此時遞迴的深度為
(
表示連結串列的節點數),然後再逐層返回,每次都修改當前節點的 next
指標。
Java 實現
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode p = reverseList(head.next);
head.next.next = head;
head.next = null;
return p;
}
}
Python 實現
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if head == None or head.next == None:
return head
p = self.reverseList(head.next)
head.next.next, head.next = head, None
return p
複雜度分析
- 時間複雜度: ,其中 表示連結串列的節點數
- 空間複雜度: ,額外的空間是由於遞迴呼叫佔用系統棧的空間,遞迴的深度最多為 層