-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathList.cpp
129 lines (129 loc) · 2.53 KB
/
List.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
#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
};
typedef struct Node* node;
//cap phat dong mot node moi voi du lieu la so nguyen x
node makeNode(int x){
node tmp = new Node();
tmp->data = x;
tmp->next = NULL;
return tmp;
}
//kiem tra rong
bool empty(node a){
return a == NULL;
}
//do rong (size)
int Size(node a){
int cnt =0;
while(a != NULL){
a = a->next;
}
return cnt;
}
//them 1 phan tu vao dau danh sach lien ket
void insertFirst(node &a, int val){
node tmp = makeNode(val);
if(a == NULL){
a == tmp;
}
else{
tmp->next = a;
a = tmp;
}
}
//Them mot phan tu vao cuoi danh sach
void insertLast(node &a, int val){
node tmp = makeNode(val);
if(a == NULL) a == tmp;
else{
node p = a;
while(p->next != NULL){
p = p->next;
}
p->next = tmp;
}
}
//them mot phan tu vao giua
void insertMiddle(node &a, int val, int pos){
int n = Size(a);
if(pos <= 0 || pos > n + 1){
cout<<"Error";
}
if(pos == 1){
insertFirst(a,x);
return;
}
else if(pos == n + 1){
insertLast(a,x);
return;
}
node p = a;
for(int i =1; i < pos - 1; i++){
p = p->next;
}
node tmp = makeNode(val);
tmp->next = p->next;
p->next = tmp;
}
//xoa phan tu o dau
void deleteFirst(node &a){
if(a == NULL) return;
a = a->next;
}
//xoa phan tu o cuoi
void deleteLast(node &a){
if(a == NULL) return;
node truoc = NULL, sau = a;
while(sau->next != NULL){
truoc = sau;
sau = sau->next;
}
if(truoc == NULL){
a == NULL;
}
else{
truoc->next = NULL;
}
}
//xoa phan tu o giua
void deleteMiddle(node &a, int pos){
int n = Size(a);
if(pos <= 0 || pos > n) return;
node truoc = NULL, sau = a;
for(int i = 1; i < pos; i++){
truoc = sau;
sau = sau->next;
}
if(truoc == NULL){
a = a->next;
}
else{
truoc->next = sau->next;
}
}
//print
void in(node a){
cout << "--------------------------------\n";
while(a != NULL){
cout<<a->data<<" ";
a = a->next;
}
cout<<endl;
}
void sapxep(node &a){
for(node p = a; p->next != NULL; p = p->next){
node min = p;
for(node q = p->next; q != NULL; q = q->next){
if(q->data < min->data){
min = q;
}
}
int tmp = min->data;
min->data = p->data;
p->data = tmp;
}
}