解题思路
迭代:
Python
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseList(self, head):
pre = None
cur = head
while cur:
temp = cur.next
cur.next = pre
pre = cur
cur = temp
return pre
C++
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode * curr = head;
ListNode * pre = nullptr;
ListNode * temp = curr;
while(curr){
curr = curr->next;
temp->next = pre;
pre = temp;
temp = curr;
}
return pre;
}
};
复杂度分析:
- 时间复杂度:O(n),其中 n 是链表的长度。需要遍历链表一次;
- 空间复杂度:O(1)。
递归
- 使用递归函数,一直递归到链表的最后一个结点,该结点就是反转后的头结点,记作pre。
- 此后,每次函数在返回的过程中,让head结点的下一个结点的next指针指向head。
- 同时让head结点的next指针指向None,从而实现从链表尾部开始的局部反转。
- 当递归函数全部出栈后,链表反转完成。
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
pre = self.reverseList(head.next)
head.next.next = head
head.next = None
return pre
c++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr || head->next == nullptr) {
return head;
}
ListNode* last = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return last;
}
};