-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDoubleList.cpp
140 lines (125 loc) · 2.44 KB
/
DoubleList.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
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
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
struct Node
{
Node(int data = 0) : data_(data), next_(nullptr), prev_(nullptr){}
int data_;
Node* next_;
Node* prev_;
};
//双向链表
class doubleList
{
public:
doubleList()
{
head_ = new Node();
}
~doubleList()
{
Node* p = head_;
while(p)
{
head_ = head_->next_;
delete p;
p = head_;
}
}
//在头部插入元素 O(1)
void insertHead(int val)
{
Node* node = new Node(val);
node->next_ = head_->next_;
node->prev_ = head_;
if(head_->next_)
{
head_->next_->prev_ = node;
}
head_->next_ = node;
}
//在尾部插入元素 O(n)
void insertTail(int val)
{
Node* p = head_;
while(p->next_)
{
p = p->next_;
}
Node* node = new Node(val);
node->prev_ = p;
p->next_ = node;
}
//删除元素 O(n)
void remove(int val)
{
Node* p = head_->next_;
while(p)
{
if(p->data_ == val)
{
auto next = p->next_;
p->prev_->next_ = p->next_;
if(p->next_)
{
p->next_->prev_ = p->prev_;
}
delete p;
p = next;
}
else
{
p = p->next_;
}
}
}
//查找元素 O(n)
bool find(int val)
{
Node* p = head_->next_;
while(p)
{
if(p->data_ == val)
{
return true;
}
else
{
p = p->next_;
}
}
return false;
}
//输出双向链表的元素
void show()
{
Node* p = head_->next_;
while(p)
{
cout << p->data_ << " ";
p = p->next_;
}
cout << endl;
}
private:
Node* head_;
};
int main(int argc, char* argv[])
{
doubleList dlist;
srand(time(0));
for(int i = 0; i < 10; ++i)
{
int val = rand() % 100;
dlist.insertTail(val);
}
dlist.show();
dlist.insertHead(100);
dlist.insertHead(100);
dlist.show();
cout << boolalpha << dlist.find(100) << endl;
dlist.remove(100);
dlist.show();
return 0;
}