下面实现的是一个简单的单链表
功能不多,学习使用
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
|
#pragma once #include <iostream> using
namespace std;
class
ListEx
{ private :
struct
Node
{
Node* next;
int
data;
Node( const
Node& node): data(node.data), next( nullptr ) {}
Node( const
T& d): data(d), next( nullptr ) {}
};
private :
Node* head;
int
n; //索引
public :
ListEx(): head( nullptr ), n(0) {}
Node* getp( int
pos)
{
if
(pos < 0 || pos > n)
{
return
nullptr ;
}
if
(pos == 0)
{
return
head;
}
Node* p = head;
for
( int i = 1; i < pos; i++)
{
p = p->next;
}
return
p->next;
}
void
travel()
{
Node* p = head;
if
(p == nullptr )
{
return ;
}
p = p->next;
while
(p)
{
cout << p->data << "\t"
<< endl;
p = p->next;
}
}
void
insert( int
d, int
pos = -1)
{
if
(head == nullptr )
{
head = new
Node(0);
Node* p = new
Node(d);
head->next = p;
p->next = nullptr ;
}
//添加到最后
else
if (pos < 0 || pos > n)
{
Node* p = getp(n);
Node* node = new
Node(d);
p->next = node;
node = nullptr ;
}
//添加到pos位置
else
{
Node* node = new
Node(d);
Node* p = getp(n - 1);
Node* q = p->next;
p->next = node;
node->next = q;
}
++n;
}
//从pos开始查找data 为d的元素,默认从0开始
int
find( int
d, int
pos = 0)
{
Node* p = getp(pos);
if
(p == nullptr )
{
return
-1;
}
while
(p)
{
if
(p->data == d)
{
return
pos;
}
pos++;
p = p->next;
}
return
-1;
}
//从pos开始删除data为d的元素
bool
erase( int
d, int
pos = 0)
{
int
nIndex = find(d, pos);
if
(nIndex == -1)
{
return
false ;
}
Node* p = getp(nIndex - 1);
Node* q = getp(nIndex);
if
(p == nullptr )
{
return
false ;
}
p->next = q->next;
delete
q;
return
true ;
}
}; |