206. Reverse Linked List
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL// Iteration
ListNode* reverseList(ListNode* head) { // time: O(n); space: O(1)
ListNode *pre = nullptr, *cur = head, *nex = nullptr;
while (cur) {
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
return pre;
}// Recursion
ListNode* reverseList(ListNode* head) { // time: O(n); space: O(n)
if (!head || !head->next) return head;
ListNode* node = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return node;
}Last updated