-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkList.hpp
169 lines (135 loc) · 2.39 KB
/
LinkList.hpp
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
#ifndef _LINK_LIST_HPP
#define _LINK_LIST_HPP
#include <cstddef>
#include <memory>
#include <string>
#include <cctype>
#include <vector>
#include <algorithm>
#include <iostream>
#include <assert.h>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class LinkList
{
public:
LinkList(std::string str);
LinkList(ListNode* pLstNd = nullptr);
~LinkList();
LinkList(const LinkList& lst);
LinkList operator= (const LinkList& lst);
//"{2,1,3,4}" present list: 2->1->3->4
//and parse "{2,1,3,4}"into a vector<int>:
//[2,1,3,4]
void ParseListStr();
//get a head pointer from string
ListNode* IniList();
// free all list node and reset all data
void Clear();
// reset the list to initial state
//like the string when consturct
ListNode* Reset();
//print a list
static void PrintList(ListNode* head);
private:
ListNode* head;
std::vector<int> listNode;
std::string strList;
};
LinkList::LinkList(std::string str) :head(nullptr)
{
strList = str;
ParseListStr();
}
LinkList::LinkList(ListNode* pLstNd) :head(pLstNd)
{
}
LinkList::~LinkList()
{
Clear();
}
void LinkList::ParseListStr()
{
if (strList.empty())
return;
std::string strNode;
listNode.clear();
for (auto x : strList)
{
if (std::isalnum(x))
strNode += x;
else
{
if (!strNode.empty())
listNode.push_back(atoi(strNode.c_str()));
strNode.clear();
}
}
std::reverse(listNode.begin(), listNode.end());
}
ListNode* LinkList::IniList()
{
if (0 == listNode.size())
return nullptr;
if (nullptr != head)
head = nullptr; // should clear(),but head may be
//changed outside,so head in this class
//would be a wild pointer
assert(nullptr == head);
for (auto x : listNode)
{
if (nullptr == head)
{
head = new ListNode(x);
}
else
{
ListNode* p = new ListNode(x);
p->next = head;
head = p;
}
}
return head;
}
void LinkList::PrintList(ListNode* head)
{
if (nullptr == head)
{
std::cout << "nullptr" << std::endl;
}
else
{
ListNode* p = head;
while (NULL != p)
{
std::cout << p->val << ",";
p = p->next;
}
std::cout << std::endl;
}
}
void LinkList::Clear()
{
// free memory
if (nullptr == head)
return;
ListNode* p = nullptr;
while (nullptr != head)
{
p = head;
head = head->next;
free(p);
}
head = nullptr;
}
ListNode* LinkList::Reset()
{
Clear();
//ParseListStr();
head = IniList();
return head;
}
#endif