c/c++ leetcode 翻转链表
题目描述
206. 反转链表
难度简单1133
反转一个单链表。
解法一: 迭代(最优解)
假设 第一个节点前面有一个NULL节点,
ListNode* reverseList(ListNode* head) {
if (!head || !(head -> next)) return head;
//pre 是上一个节点 curr是当前的节点 last 为 保存下一个节点
ListNode * pre = NULL, *curr = head,*last = NULL;
while (curr -> next) {
last = curr -> next;
curr -> next = pre;
pre = cur;
curr = last; //这是一次循环最后执行的语句;最后的节点curr 没有执行链接
}
//curr 原先最后一个节点 翻转后的头结点,链接原先的倒数第二个节点,现在的第二个节点
curr -> next = pre;
return curr;
}
时空复杂度
时间复杂度: 一遍循环O(N);
空间复杂度:使用了常量的变量为O(1);
解法二: 递归;
千万不要人肉递归,只需要考虑当前层的逻辑;
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//terminator 递归终止条件 有一个节点就返回 head -> next == NULL
if (!head || !(head -> next)) return head;
//1 -> 2 -> 3 -> 4 -> 5
//递归结束返回的是 4
ListNode* newHead = reverseList(head -> next);
//4 -> next = 5 ; 5 -> next = 4;
head -> next -> next = head;
//4 -> next = NULL;
head -> next = NULL;
return newHead;
}
};
时空复杂度
时间复杂度: 递归了n 次 为O(N)
空间复杂度:使用了n 个的栈空间为O(N);