206. 反转链表
题目链接
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list/submissions/
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目描述
题目分析
- 方法一:迭代法
时间复杂度o(1)
空间复杂度o(1)
最后一个结点指向空结点,所以从第一个结点反转后指向null
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *cur = head;
ListNode *pre = NULL;//cur的前一个 c++ 大写NULL
ListNode *next;//cur的下一个
while(cur != nullptr){
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}
return pre;
}
};
- 方法二:递归法
时间复杂度o(n)
空间复杂度o(n)
- 第一种写法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return reverse(NULL, head);//从null->head开始反转
}
ListNode* reverse(ListNode *pre, ListNode *cur){
if(cur == nullptr) return pre;
ListNode *next = cur->next;
cur->next = pre;
// pre = cur;递归了这两步
// cur = temp;
return reverse(cur, next);
}
};
- 第二种写法
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) return head;
ListNode* fast = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return fast;
}
};