new algo
This commit is contained in:
108
Exercise/Homework1/A 单链表基本操作.cpp
Normal file
108
Exercise/Homework1/A 单链表基本操作.cpp
Normal file
@@ -0,0 +1,108 @@
|
||||
#include <iostream>
|
||||
using namespace std;
|
||||
|
||||
template <class T>
|
||||
struct Node {
|
||||
T element;
|
||||
Node<T>* next;
|
||||
Node(const T& e, Node<T>* n = nullptr) : element(e), next(n) {}
|
||||
};
|
||||
|
||||
template <class T>
|
||||
class Chain {
|
||||
private:
|
||||
Node<T>* head;
|
||||
int size;
|
||||
|
||||
public:
|
||||
Chain() : head(nullptr), size(0) {}
|
||||
|
||||
~Chain() {
|
||||
while (head != nullptr) {
|
||||
Node<T>* tmp = head;
|
||||
head = head->next;
|
||||
delete tmp;
|
||||
}
|
||||
}
|
||||
|
||||
void insert(int pos, const T& e) {
|
||||
if (pos < 0 || pos > size) {
|
||||
throw invalid_argument("Invalid insert position");
|
||||
}
|
||||
if (pos == 0) {
|
||||
head = new Node<T>(e, head);
|
||||
} else {
|
||||
Node<T>* prev = head;
|
||||
for (int i = 0; i < pos - 1; i++) {
|
||||
prev = prev->next;
|
||||
}
|
||||
prev->next = new Node<T>(e, prev->next);
|
||||
}
|
||||
size++;
|
||||
}
|
||||
|
||||
void erase(int pos) {
|
||||
if (pos < 0 || pos >= size) {
|
||||
throw invalid_argument("Invalid erase position");
|
||||
}
|
||||
Node<T>* toDelete;
|
||||
if (pos == 0) {
|
||||
toDelete = head;
|
||||
head = head->next;
|
||||
} else {
|
||||
Node<T>* prev = head;
|
||||
for (int i = 0; i < pos - 1; i++) {
|
||||
prev = prev->next;
|
||||
}
|
||||
toDelete = prev->next;
|
||||
prev->next = toDelete->next;
|
||||
}
|
||||
delete toDelete;
|
||||
size--;
|
||||
}
|
||||
|
||||
void print() const {
|
||||
Node<T>* cur = head;
|
||||
while (cur != nullptr) {
|
||||
cout << cur->element << " ";
|
||||
cur = cur->next;
|
||||
}
|
||||
cout << endl;
|
||||
}
|
||||
};
|
||||
|
||||
int main(){
|
||||
int n;
|
||||
cin >> n;
|
||||
Chain<int> list;
|
||||
|
||||
for (int i = 0; i < n; i++) {
|
||||
int x;
|
||||
cin >> x;
|
||||
try {
|
||||
list.insert(i, x);
|
||||
}
|
||||
catch(const invalid_argument& e) {}
|
||||
}
|
||||
|
||||
int m;
|
||||
cin >> m;
|
||||
for (int i = 0; i < m; i++) {
|
||||
int op, k, d;
|
||||
cin >> op;
|
||||
if (op == 0) {
|
||||
cin >> k >> d;
|
||||
try {
|
||||
list.insert(k, d);
|
||||
} catch(const invalid_argument& e) {}
|
||||
} else if (op == 1) {
|
||||
cin >> k;
|
||||
try {
|
||||
list.erase(k - 1);
|
||||
} catch(const invalid_argument& e) {}
|
||||
}
|
||||
}
|
||||
|
||||
list.print();
|
||||
return 0;
|
||||
}
|
||||
Reference in New Issue
Block a user