summaryrefslogtreecommitdiff
path: root/top-interview-questions/easy/linked_list/03_reverse_linked_list.cc
blob: d97bd333466ad9be45b94a53aeca4bfaa440d70b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    // Reverse the list and return the head of the new list.
    ListNode* reverse(ListNode* node) {
        if (!node)       { return nullptr; }
        if (!node->next) { return node; }
        ListNode* head = reverse(node->next);
        node->next->next = node;
        node->next = nullptr;
        return head;
    }

    ListNode* reverseList(ListNode* head) {
        return reverse(head);
    }
};