单链表的插入操作的实现

建立长度为n的单链表,在第i个结点之前插入数据元素data。
Description
第一行为自然数n,表示链式线性表的长度; 
第二行为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;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值