9033:单链表的插入

23 篇文章 0 订阅

 Problem Description

建立单链表,在第n个结点后插入指定结点,并完成遍历操作。

 Input

输入数据有多组,每组数据占两行:
第一行有两个数字(n,m),第一个数n表示结点位置,第二个数表示指定需插入的数。后跟单链表各结点(不会超过100),以0结束一个单链表。

例如:
3 5
1 2 3 4 5 0
0 0
遇到0 0,结束程序。

 Output

输出插入后的单链表,每组输出占一行,每个元素之间有一个空格。

 Sample Input

3 5
1 2 3 4 5 0
0 0

 Sample Output

1 2 3 5 4 5
#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

struct node {
    int data;
    node* next;
};

class List {
public:
    node* head;
    List() {
        head=new node;
        head->next=NULL;
    }
    void creat() {
        node* r=head;
        int num;
        while(cin>>num&&num!=0) {

            //   if(num==0)break;
            node* s=new node;
            s->data=num;
            r->next=s;
            r=s;
        }
        r->next=NULL;
    }


    void Insert(int index,int data) {
        int count=0;
        node* p=head;
        while(p->next&&count++<index) {
            p=p->next;
        }
        node* s=new node;
        s->data=data;
        s->next=p->next;
        p->next=s;

    }





    ~List() {
        //     if(head==NULL||head->next==NULL)return;
        node* p=head->next;
        while(p) {
            node* temp=p;
            p=p->next;
            delete temp;
        }
    }

    void print() {

        if(head->next==NULL||head==NULL) {
            return;
        }
        node* p=head->next;
        while(p->next) {

            cout<<p->data<<" ";
            p=p->next;

        }
        cout<<p->data<<endl;
    }


};


int main() {
    
    int index,data;
    while(cin>>index>>data) {
        //  cout<<index<<endl<<data<<endl;
        if(index==0&&data==0)
            return 0;
        else {

            List list;
            list.creat();
            list.Insert(index,data);
            list.print();
        }
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haibianyoushark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值