1.已知有一带头结点的单链表LA,用尾插法构建单链表LA,让其元素与一维数组a[]={3,5,8,11}元素相同,在单链表LA中第i(1<=i<=5)个位置之前插入新的元素e(e的值为任意整数)。运行后显示效果如下图:【源程序保存为Insert.cpp】
时间: 2024-04-30 18:22:52 浏览: 4
```c++
#include<iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
int main() {
int a[] = {3, 5, 8, 11};
Node* head = new Node;
Node* tail = head;
for (int i = 0; i < 4; i++) {
Node* p = new Node;
p->data = a[i];
p->next = NULL;
tail->next = p;
tail = p;
}
cout << "插入前的单链表:";
Node* p = head->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
int pos;
cout << "请输入要插入的位置(1~5):";
cin >> pos;
Node* q = head;
for (int i = 1; i < pos; i++) {
q = q->next;
}
Node* r = new Node;
r->data = 7;
r->next = q->next;
q->next = r;
cout << "插入后的单链表:";
p = head->next;
while (p != NULL) {
cout << p->data << " ";
p = p->next;
}
cout << endl;
return 0;
}
```