diff options
Diffstat (limited to 'top-interview-questions/easy/linked_list/03_reverse_linked_list.cc')
-rw-r--r-- | top-interview-questions/easy/linked_list/03_reverse_linked_list.cc | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/top-interview-questions/easy/linked_list/03_reverse_linked_list.cc b/top-interview-questions/easy/linked_list/03_reverse_linked_list.cc new file mode 100644 index 0000000..d97bd33 --- /dev/null +++ b/top-interview-questions/easy/linked_list/03_reverse_linked_list.cc | |||
@@ -0,0 +1,26 @@ | |||
1 | /** | ||
2 | * Definition for singly-linked list. | ||
3 | * struct ListNode { | ||
4 | * int val; | ||
5 | * ListNode *next; | ||
6 | * ListNode() : val(0), next(nullptr) {} | ||
7 | * ListNode(int x) : val(x), next(nullptr) {} | ||
8 | * ListNode(int x, ListNode *next) : val(x), next(next) {} | ||
9 | * }; | ||
10 | */ | ||
11 | class Solution { | ||
12 | public: | ||
13 | // Reverse the list and return the head of the new list. | ||
14 | ListNode* reverse(ListNode* node) { | ||
15 | if (!node) { return nullptr; } | ||
16 | if (!node->next) { return node; } | ||
17 | ListNode* head = reverse(node->next); | ||
18 | node->next->next = node; | ||
19 | node->next = nullptr; | ||
20 | return head; | ||
21 | } | ||
22 | |||
23 | ListNode* reverseList(ListNode* head) { | ||
24 | return reverse(head); | ||
25 | } | ||
26 | }; | ||