Reverse Linked List
- leetcode: Reverse Linked List | LeetCode OJ
- lintcode:
temp = head->next;
head->next = prev;
prev = head;
head = temp;
要点在于维护两个指针变量prev
和head
, 翻转相邻两个节点之前保存下一节点的值,分析如下图所示:
- 保存head下一节点
- 将head所指向的下一节点改为prev
- 将prev替换为head,波浪式前进
- 将第一步保存的下一节点替换为head,用于下一次循环
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head) {
ListNode *prev = NULL;
while (curr != NULL) {
ListNode *temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
head = prev;
return head;
}
};
Java
复杂度分析
遍历一次链表,时间复杂度为 O(n), 使用了辅助变量,空间复杂度 O(1).
递归的终止步分三种情况讨论:
- 原链表为空,直接返回空链表即可。
- 原链表仅有一个元素,返回该元素。
- 原链表有两个以上元素,由于是单链表,故翻转需要自尾部向首部逆推。
Python
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param head: The first node of the linked list.
@return: You should return the head of the reversed linked list.
Reverse it in-place.
"""
def reverse(self, head):
# case1: empty list
if head is None:
return head
# case2: only one element list
if head.next is None:
# case3: reverse from the rest after head
# reverse between head and head->next
head.next.next = head
# unlink list from the rest
head.next = None
return newHead
Java
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverse(ListNode head) {
// case1: empty list
if (head == null) return head;
// case2: only one element list
if (head.next == null) return head;
// case3: reverse from the rest after head
ListNode newHead = reverse(head.next);
// reverse between head and head->next
head.next.next = head;
// unlink list from the rest
head.next = null;
return newHead;
}
源码分析
case1 和 case2 可以合在一起考虑,case3 返回的为新链表的头节点,整个递归过程中保持不变。
递归嵌套层数为 O(n), 时间复杂度为 O(n), 空间(不含栈空间)复杂度为 O(1).