-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1.cpp
101 lines (88 loc) · 1.94 KB
/
1.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
//第一次上机作业:建立一个顺序表,插入,删除,定位查找删除。
#include <iostream>
using namespace std;
// 定义顺序表类
class SeqList {
private:
int *arr; // 存储数据的数组
int size; // 当前元素个数
int capacity; // 数组容量
public:
SeqList(int cap) {
capacity = cap;
size = 0;
arr = new int[capacity];
}
// 插入元素
void insert(int index, int value) {
if (index < 0 || index > size) {
cout << "Index out of bounds!" << endl;
return;
}
if (size == capacity) {
cout << "List is full!" << endl;
return;
}
for (int i = size; i > index; --i) {
arr[i] = arr[i - 1];
}
arr[index] = value;
size++;
}
// 删除元素
void remove(int index) {
if (index < 0 || index >= size) {
cout << "Index out of bounds!" << endl;
return;
}
for (int i = index; i < size - 1; ++i) {
arr[i] = arr[i + 1];
}
size--;
}
// 定位查找
int locate(int value) {
for (int i = 0; i < size; ++i) {
if (arr[i] == value) {
return i; // 返回元素位置
}
}
return -1; // 未找到
}
// 查找并删除指定元素
void findAndRemove(int value) {
int index = locate(value);
if (index != -1) {
remove(index);
cout << "Element " << value << " removed." << endl;
} else {
cout << "Element not found!" << endl;
}
}
// 打印顺序表
void print() {
for (int i = 0; i < size; ++i) {
cout << arr[i] << " ";
}
cout << endl;
}
~SeqList() {
delete[] arr;
}
};
int main() {
SeqList list(10);
list.insert(0, 10);
list.insert(1, 20);
list.insert(2, 30);
list.insert(1, 15);
cout << "List after insertions: ";
list.print();
list.remove(2);
cout << "List after removing element at index 2: ";
list.print();
list.findAndRemove(15);
cout << "List after removing element 15: ";
list.print();
return 0;
}