建立长度为n的单链表,在第i个结点之前插入数据元素data。
Description
第一行为自然数n,表示链式线性表的长度;
第二行为n个自然数表示链式线性表各元素值;
第三行为指定插入的位置i;第四行为待插入数据元素data。
第二行为n个自然数表示链式线性表各元素值;
第三行为指定插入的位置i;第四行为待插入数据元素data。
Input
指定插入位置合法时候,输出插入元素后的链式线性表的所有元素,元素之间用一个空格隔开。输入不合法,输出"error!"。
Output
1
2
3
4
5
|
5
1 2 3 4 5
3
6
|
Sample Input
1
2
|
1 2 6 3 4 5
|
#include <iostream>
#include <malloc.h>
using namespace std;
typedef struct node{
int data;
struct node *next;
}LinkList;
int main(){
int n;
cin>>n;
LinkList *l,*end,*body;
l=(LinkList*)malloc(sizeof(LinkList));
end=l;
int num;
for(int i=0;i<n;i++){
cin>>num;
body=(LinkList*)malloc(sizeof(LinkList));
body->data=num;
end->next=body;
end=body;
}
end->next=NULL;
int index,toAddData;
cin>>index;
cin>>toAddData;
if(index>=0&&index<n){
LinkList *templ=l;
int i=0;
while(i<index-1){
i++;
templ=templ->next;
}
LinkList *tempBody=(LinkList*)malloc(sizeof(LinkList));
tempBody->data=toAddData;
tempBody->next=templ->next;
templ->next=tempBody;
LinkList *head=l->next;
while(head->next!=NULL){
cout<<head->data<<' ';
head=head->next;
}
cout<<head->data<<' ';
}else{
cout<<"error!";
}
return 0;
}