-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path206_Reverse Linked List.cpp
More file actions
59 lines (51 loc) · 1.21 KB
/
Copy path206_Reverse Linked List.cpp
File metadata and controls
59 lines (51 loc) · 1.21 KB
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
#include <iostream>
using namespace std;
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution { // iterative
public:
ListNode* reverseList(ListNode* head) {
// corner cases
if (!head || !head->next) return head;
// reverse linkedlist
ListNode *pre = NULL, *cur = head, *next = head;
while (cur) {
next = cur->next;
cur->next = pre;
pre = cur; cur = next;
}
// final result
return pre;
}
};
class Solution { // recursion
public:
ListNode* reverseList(ListNode* head) {
return reverse(head, NULL);
}
ListNode* reverse(ListNode *curr, ListNode *prev) {
if (!curr) return prev;
ListNode *next = curr->next;
curr->next = prev;
return reverse(next, curr);
}
};
int main() {
ListNode* a = new ListNode(1);
ListNode* b = new ListNode(2);
ListNode* c = new ListNode(3);
ListNode* d = new ListNode(4);
ListNode* e = new ListNode(5);
a->next = b; b->next = c; c->next = d; d->next = e; e->next = NULL;
Solution sol;
ListNode *head = sol.reverseList(a);
while (head) {
cout << head->val << " ";
head = head->next;
}
return 0;
}