7-1 单链表基本操作
请编写程序实现单链表插入、删除结点等基本算法。给定一个单链表和一系列插入、删除结点的操作序列,输出实施上述操作后的链表。单链表数据域值为整数。
输入格式:
输入第1行为1个正整数n,表示当前单链表长度;第2行为n个空格间隔的整数,为该链表n个元素的数据域值。第3行为1个正整数m,表示对该链表施加的操作数量;接下来m行,每行表示一个操作,为2个或3个整数,格式为0 k d或1 k。0 k d表示在链表第k个结点后插入一个数据域值为d的结点,若k=0则表示表头插入。1 k表示删除链表中第k个结点,此时k不能为0。注:操作序列中若含有不合法的操作(如在长度为5的链表中删除第8个结点、删除第0个结点等),则忽略该操作。n和m不超过100000。
输出格式:
输出为一行整数,表示实施上述m个操作后的链表,每个整数后一个空格。输入数据保证结果链表不空。
输入样例:
5
1 2 3 4 5
5
0 2 8
0 9 6
0 0 7
1 0
1 6
输出样例:
7 1 2 8 3 5
include
include
using namespace std;
struct Node {
int data;
Node* next;
Node(int data) : data(data), next(nullptr) {}
};
void insert(Node& head, int pos, int data) {
Node node = new Node(data);
if (pos == 0) {
node->next = head;
head = node;
} else {
Node* current = head;
for (int i = 0; i < pos - 1 && current != nullptr; ++i) {
current = current->next;
}
if (current != nullptr) {
node->next = current->next;
current->next = node;
}
}
}
void remove(Node& head, int pos) {
if (pos == 0 && head != nullptr) {
Node toDelete = head;
head = head->next;
delete toDelete;
} else {
Node* current = head;
for (int i = 0; i < pos - 1 && current != nullptr; ++i) {
current = current->next;
}
if (current != nullptr && current->next != nullptr) {
Node* toDelete = current->next;
current->next = current->next->next;
delete toDelete;
}
}
}
void printList(Node* head) {
Node* current = head;
while (current != nullptr) {
cout << current->data << " ";
current = current->next;
}
}
int main() {
int n, m, data, op, pos;
cin >> n;
cin >> data;
Node* head = new Node(data);
Node* tail = head;
for (int i = 1; i < n; ++i) {
cin >> data;
tail->next = new Node(data);
tail = tail->next;
}
cin >> m;
for (int i = 0; i < m; ++i) {
cin >> op >> pos;
if (op == 0) { // insert
cin >> data;
insert(head, pos, data);
} else if (op == 1 && pos > 0 && pos <= n + i) { // remove
remove(head, pos - 1);
}
}
printList(head);
return 0;
}