-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
107 lines (94 loc) · 2.23 KB
/
main.cpp
File metadata and controls
107 lines (94 loc) · 2.23 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
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
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <vector>
#include <stack>
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:
void print_list(ListNode* head)
{
int i = 1;
ListNode* ptr = head;
while (ptr != NULL)
{
std::cout << i << ": " << ptr->val << std::endl;
ptr = ptr->next;
i++;
}
}
ListNode* create_list(ListNode* ptr, vector<int>& nums)
{
ListNode* last_ptr = ptr;
if (last_ptr == NULL)
last_ptr = new ListNode(nums[0]);
else
last_ptr->next = new ListNode(nums[0]);
ListNode* head = last_ptr;
while (last_ptr->next != NULL)
last_ptr = last_ptr->next;
for (int i = 1; i < (int)nums.size(); ++i)
{
last_ptr->next = new ListNode(nums[i]);
last_ptr = last_ptr->next;
}
last_ptr->next = NULL;
return head;
}
void delete_element(ListNode* element)
{
while (element != nullptr)
{
ListNode* temp = element;
element = element->next;
delete temp;
}
}
void delete_list(ListNode* head)
{
delete_element(head);
}
ListNode* reverseList(ListNode* head)
{
if (head == NULL)
return NULL;
ListNode* ptr = head;
stack<ListNode*> ptrs;
while (ptr != NULL)
{
ptrs.push(ptr);
ptr = ptr->next;
}
ListNode* new_head = ptr = ptrs.top();
ptrs.pop();
while (!ptrs.empty())
{
ptr->next = ptrs.top();
ptrs.pop();
ptr = ptr->next;
}
ptr->next = NULL;
return new_head;
}
};
int main()
{
ListNode* head = NULL;
vector<int> nums = { 1, 2, 3, 4, 5 };
Solution solution;
head = solution.create_list(head, nums);
head = solution.reverseList(head);
solution.print_list(head);
solution.delete_list(head);
return 0;
}