思路参考:Leetcode精选题解:动画演示+多种解法 206. 反转链表
原地翻转
时间复杂度 O(n) 空间复杂度 O(1)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=NULL,*cur=head,*next;
while(cur!=NULL){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
递归解法:
时间复杂度 O(n) 空间复杂度 O(n)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL) return head;
ListNode * cur = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return cur;
}
};