-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_linked_list.cpp
83 lines (75 loc) · 1.63 KB
/
reverse_linked_list.cpp
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* =====================================================================================
*
* Filename: reverse_linked_list.cpp
*
* Description: 206. Reverse Linked List.
*
* Version: 1.0
* Created: 04/11/19 03:11:07
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng (), [email protected]
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
// Iterative
class Solution1
{
public:
ListNode* reverseList(ListNode* head)
{
ListNode fake(0);
ListNode* ptr = head;
ListNode* tmp = NULL;
while (ptr != NULL)
{
tmp = ptr->next;
ptr->next = fake.next;
fake.next = ptr;
ptr = tmp;
}
return fake.next;
}
};
// Recursive
class Solution2
{
public:
ListNode* reverseList(ListNode* head)
{
ListNode* tail = NULL;
return reverseList(head, &tail);
}
private:
ListNode* reverseList(ListNode* head, ListNode** tail)
{
if (head == NULL || head->next == NULL)
{
*tail = head;
return head;
}
ListNode* ptr = reverseList(head->next, tail);
(*tail)->next = head;
head->next = NULL;
*tail = head;
return ptr;
}
};
using Solution = Solution2;
int main(int argc, char* argv[])
{
ListNode head(0);
auto* reverse = Solution().reverseList(&head);
return 0;
}