#include <iostream>
class MyLinkedList {
public:
//定义链表节点结构体
struct LinkedNode {
int val;
LinkedNode* next;
LinkedNode(int x) :val(x), next(NULL) {};
};
//初始化链表
MyLinkedList() {
dummyHead = new LinkedNode(0);
length = 0;
}
//析构函数
~MyLinkedList() {
while (dummyHead) {
LinkedNode* tmp = dummyHead;
dummyHead = dummyHead->next;
delete tmp;
}
}
//尾插法
void AddTail(int value) {
LinkedNode* newnode = new LinkedNode(value);
LinkedNode* cur = dummyHead;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newnode;
length++;
}
//判断索引是否合法
bool Is_Legal(int index) {
if (index<0 || index>length - 1) {
return false;
}
else return true;
}
//第index个数前插入value
void Insert(int index, int value) {
LinkedNode* newnode = new LinkedNode(value);
LinkedNode* cur = dummyHead;
index--;
while (index--) {
cur = cur->next;
}
newnode->next = cur->next;
cur->next = newnode;
length++;
}
//打印链表
void PrintLinkedList() {
LinkedNode* cur = dummyHead;
while (cur->next != NULL) {
std::cout << cur->next->val << " ";
cur = cur->next;
}
}
private:
LinkedNode* dummyHead;//虚拟头结点
int length;
};
int main() {
MyLinkedList list;
int n, a;
std::cin >> n;
while (n--) {
std::cin >> a;
list.AddTail(a);
}
int i;
std::cin >> i >> a;
if (list.Is_Legal(i)) {
list.Insert(i, a);
list.PrintLinkedList();
}
else std::cout << "error!";
return 0;
}
【STL】
#include<iostream>
#include<vector>
#include<algorithm>
int main() {
int n;
std::cin >> n;
std::vector<int> vec(n);
for (int i = 0; i < n; i++) std::cin >> vec[i];
int i, data;
std::cin >> i >> data;
if (i >= 0 && i <= n) {
vec.insert(vec.begin() + i - 1, data);
for (int a : vec) {
std::cout << a << " ";
}
}
else std::cout << "error!";
return 0;
}