学习版
【C语言】
需要扩充数组
【C++】
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class MyLinkedList
{
public:
struct LinkedNode
{
int val;
LinkedNode* next;
LinkedNode(int x) :val(x), next(NULL) {}
};
MyLinkedList() {
dummyHead = new LinkedNode(0);
len = 0;
}
~MyLinkedList() {
while (dummyHead) {
LinkedNode* tmp = dummyHead;
dummyHead = dummyHead->next;
delete tmp;
}
}
void addTail(int x) {
LinkedNode* newNode = new LinkedNode(x);
LinkedNode* cur = dummyHead;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = newNode;
len++;
}
void insert(int item, int data)
{
LinkedNode* cur = dummyHead;
LinkedNode* newNode = new LinkedNode(data);
len++;
while (cur->next != NULL && cur->next->val != item) {
cur = cur->next;
}
if (cur->next == NULL) cur->next = newNode;
else {
newNode->next = cur->next;
cur->next = newNode;
}
}
void printLinkedList() {
LinkedNode* cur = dummyHead;
while (cur->next != NULL) {
cout << cur->next->val << " ";
cur = cur->next;
}
}
private:
LinkedNode* dummyHead;
int len;
};
int main()
{
MyLinkedList list;
int n, x;
cin >> n;
while (n--) {
cin >> x;
list.addTail(x);
}
int item, data;
cin >> item;
cin >> data;
list.insert(item, data);
list.printLinkedList();
return 0;
}
【STL】
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
int n, a;
std::cin >> n;
std::vector<int> list;
while (n--) {
std::cin >> a;
list.push_back(a);
}
int item, data;
std::cin >> item >> data;
std::vector<int>::iterator it = std::find(list.begin(), list.end(), item);
list.insert(it, data);
for (int a : list) {
std::cout << a << " ";
}
return 0;
}