建立长度为n的单链表,在第i个结点之前插入数据元素data。
第一行为自然数n,表示链式线性表的长度;
第二行为n个自然数表示链式线性表各元素值;
第三行为指定插入的位置i;第四行为待插入数据元素data。
指定插入位置合法时候,输出插入元素后的链式线性表的所有元素,元素之间用一个空格隔开。输入不合法,输出"error!"。
----------------------------
1
1
1
2
------------------------------
2 1
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node
{
int data;
struct node *next;
};
int main()
{
struct node *head,*p,*q,*temp,*t;
int num,insertnum,insert;
while(cin>>num)
{
head=(struct node*)malloc(sizeof(struct node));
p=head;
for(int i=0;i<num;i++)
{
q=(struct node*)malloc(sizeof(struct node));
cin>>q->data;
p->next=q;
p=q;
}
p->next=NULL;
temp=head;
cin>>insertnum>>insert;
if(insertnum>num)
{
cout<<"error!";
break;
}
else
{
int j=0;
while(j<insertnum-1)
{
j++;
temp=temp->next;
}
if(temp==NULL) return false;//内存不存在,终结;
t=(struct node *)malloc(sizeof(struct node));
t->data=insert;
t->next=temp->next;
temp->next=t;
}
temp=head;
while(temp->next!=NULL)
{
cout<<temp->next->data<<" ";
temp=temp->next;
}
}
return 0;
}
--------------------------
i下面贴一个不是我写的版本的版本
-------------------------
#include<stdio.h>
#include<stdlib.h>
typedef int ElemType;
typedef struct node
{
ElemType Data;
struct node *next;
}SqList;
void creatlistR(SqList *&L,int n)
{
SqList *r,*s;
int i;
L=(struct node*)malloc(sizeof(struct node));
r=L;
for(i=0;i<n;i++)
{
s=(node*)malloc(sizeof(node));
scanf("%d",&s->Data);
r->next=s;
r=s;
}
r->next=NULL;
}
bool ListInsert( node *&L,int i,int date)
{
SqList *p=L,*s;
int j=0;
while(j<i-1 && p!=NULL)
{
j++;
p=p->next;
}
if(p == NULL)
{
return false;
}
else
{
s=(struct node*)malloc(sizeof(struct node));
s->Data=date;
s->next=p->next;
p->next=s;
return true;
}
}
int main()
{
int n,i;
scanf("%d",&n);
SqList *L;
creatlistR(L,n);
scanf("%d",&i);
ElemType data;
scanf("%d",&data);
if(ListInsert(L,i,data)==false)
printf("error!");
else
{
SqList *p=L->next;
while(p!=NULL)
{
printf("%d ",p->Data);
p=p->next;
}
}
return 0;
}