先看一手题吧
说实话,我刚看见这道题的时候还没学单链表,就想用其他方法来做。分析题后了解到这道题只用实现一个插入的操作,而实现插入操作的放松有很多,比如:
- 通过数组的方式来实现插入,不过这样的话,查找时间复杂度为O(1),插入时间复杂度为O(n)因为咱们是以数组下标来表示这个数的位置,所以查找为O(1),
- 再说插入,咱们用数组的话,对插入数据得将所有在该位置之后的数往后挪一位,最坏的时间复杂度即为在1的时候插入为O(n)。
-
int a[size] void insert(int a[],int n,int m) { for(int i = lenth;i > n ; i -- ) { a[i+1]=a[i];//以此往后挪一位,lenth为数组中元素的数量。 } a[n+1]=m;//插入数据。 }
2.上文是数组插入方法,现在介绍一个类似的。咱们可以创建一个动态数组vector ,它自带的函数insert可以更方便的完成此操作,当然,时间复杂度仍然是O(n),只不过让我们少写几行代码。
vector<int>a;
a.insert(a.begin()+k-1,m);//k为插入位置,m为插入数据
3.这第三那必然是咱们的链表了,说实话,我是很讨厌写这么长的,毕竟本人巨懒,懒到连return都不想写,if都写三目运算符。
好了,言归正传,咱们要用链表就先创建一个链表。
typedef struct node{
int data;
node *next;
}node;
void creat(node *&L,int n,int a[]){
node *p;
L=(node*)malloc(sizeof(node));//申请节点空间.
p=L;//让p指针指向L的地址。
L->next=NULL;//首元结点置空;
for(int i = 0 ; i < n; i ++ ) {
node *s;
s=(node*)malloc(sizeof(node));//申请结点空间,创建新结点。
s->data = a[i];
s->next=p->next;
p->next=s;//这里采用的头插法捏,至于为什么,你给我把文章看完就知道了。
}
}
咱们把链表建好以后就要开始插入数据啦,
//先把插入函数写好。
void insert(node *&L,int n,int m){//在n结点之后插入m;
node *p;
p=L;
int sum=0;/*没别的意思,就记录一下结点id,如果不要这玩意的话,在创建链表的时候可以再加一个数据,来记录结点id,这里我就不说怎么写了(本人巨懒)*/
while(sum<n-1&&p!=NULL){//找结点,而且要防止结点为空喔。
sum++;
p=p->next;
}
//咱们找到结点后,就开始插入咯。
node *s;
s=(node*)malloc(sizeof(node));//老规矩,创建结点喔。
s->data=m;
s->next=p->next;
p->next=s;
}
自此咱们的插入操作结束啦,嗯,想要答案吗?
不给(狗头保命)
好了,上文所说的头插法不适用于该题,这题得用尾插法,我相信你们应该知道怎么写,对吧?
行啦,我附上我的ac代码吧,希望能帮到你们。(不要直接copy喔,挂科警告)
#include <iostream>
#include <malloc.h>
using namespace std;
int a[100];
typedef struct node{
int data;
node *next;
}node;
void creatnode(node *&L,int a[],int n){
L=(node*)malloc(sizeof(node));
L->next=NULL;
node *q;
for(int i = 0 ; i < n ; i ++ ) {
q=(node*)malloc(sizeof(node));
node *s=L;
while(s->next!=NULL){
s=s->next;
}
s->next=q;
q->data=a[i];
q->next=NULL;
}
}
void insert(node *&L,int n,int m){
node *p;
p=L;
int i=0;
while(i<n-1&&p!=NULL){
i++;
p=p->next;
}
node *q;
q=(node*)malloc(sizeof(node));
q->data=m;
q->next=p->next;
p->next=q;
}
void print(node *&L){
node *p;
p=L->next;
while(p!=NULL){
cout << p->data << " ";
p=p->next;
}
}
int main(){
int n,m,t;
cin >> t;
for(int i = 0 ; i < t ; i ++ ) {
cin >> a[i];
}
cin >> n >> m;
if(n>t){
cout << "error!";
}
else{
node *L;
creatnode(L,a,t);
insert(L,n,m);
print(L);
}
}