-
Notifications
You must be signed in to change notification settings - Fork 0
/
200317-2.cpp
64 lines (58 loc) · 951 Bytes
/
200317-2.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
// https://leetcode-cn.com/problems/reverse-linked-list/
// 迭代法
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* q = NULL;
for (ListNode* p = head; p;) {
ListNode* next = p->next;
p->next = q;
q = p;
p = next;
}
return q;
}
};
ListNode* init(initializer_list<int>&& a)
{
ListNode node(0);
ListNode* p = &node;
for (auto it = a.begin(); it != a.end(); ++it) {
p->next = new ListNode(*it);
p = p->next;
}
return node.next;
}
void print(ListNode* l)
{
for (ListNode* p = l; p; p = p->next) {
cout << p->val << " ";
}
cout << endl;
}
void release(ListNode* p)
{
if (p) {
release(p->next);
delete p;
}
}
int main()
{
Solution s;
{
ListNode* p = init({1,2,3,4,5});
print(p);
p = s.reverseList(p);
print(p);
release(p);
}
return 0;
}