剑指 Offer 24. 反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
递归1
递归的过程建立新的节点实现反转,这样空间复杂度是O(N)
class Solution {
public:
ListNode* Node = new ListNode(0);
ListNode *node = Node;
ListNode* reverseList(ListNode* head) {
if(head == NULL)
{
return head;
}
if(head->next!=NULL)
{
reverseList(head->next);
}
node ->next = new ListNode(head->val);
node = node ->next;
return Node->next;
}
};
递归2
时间复杂度 O(N) : 遍历链表使用线性大小时间。
空间复杂度 O(N) : 遍历链表的递归深度达到N ,系统使用 O(N) 大小额外空间。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return fanzhuan(head,NULL);
}
ListNode* fanzhuan(ListNode* cur,ListNode* pre)
{
if (cur == nullptr) return pre; // 终止条件
ListNode* res = fanzhuan(cur->next, cur);
cur->next = pre;
return res;
}
};
}
};
迭代
复杂度分析:
时间复杂度 O(N) : 遍历链表使用线性大小时间。
空间复杂度 O(1) : 变量 pre 和 cur 使用常数大小额外空间。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = NULL;
ListNode* tmp ;
while(cur!=NULL)
{
tmp = cur;
cur = cur->next;
tmp->next = pre;
pre = tmp;
}
return pre;
}
};