-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathleetcode206_reverse_linked_list_v2.cpp
94 lines (75 loc) · 1.73 KB
/
leetcode206_reverse_linked_list_v2.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
84
85
86
87
88
89
90
91
92
93
94
/*
* leetcode206_reverse_linked_list.cpp
*
* @author Wang Guibao ([email protected])
* @date 2023/10/12 14:50
* @brief https://leetcode.com/problems/reverse-linked-list
*/
#include <iostream>
#include <vector>
using namespace std;
/**
* 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:
ListNode* reverseList(ListNode* head) {
ListNode pivot;
ListNode* h = head;
while (h) {
ListNode* p = h;
h = h->next;
p->next = pivot.next;
pivot.next = p;
}
return pivot.next;
}
};
ListNode* vecToList(std::vector<int> nums) {
ListNode pivot;
ListNode* p = &pivot;
int len = nums.size();
for (int i = 0; i < len; ++i) {
ListNode* node = new ListNode(nums[i]);
p->next = node;
p = p->next;
}
return pivot.next;
}
void printList(ListNode* l) {
ListNode* p = l;
while (p) {
std::cout << p->val << " ";
p = p->next;
}
std::cout << endl;
}
int main() {
while (1) {
std::vector<int> nums;
int n = 0;
std::cout << "Number of interges: ";
if (!(std::cin >> n)) {
return 0;
}
std::cout << n << " integers: ";
for (int i = 0; i < n; ++i) {
int x;
std::cin >> x;
nums.push_back(x);
}
ListNode* l = vecToList(nums);
printList(l);
Solution solution;
auto ret = solution.reverseList(l);
printList(ret);
}
return 0;
}