9033:单链表的插入

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39993896/article/details/83351204

 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;
}

猜你喜欢

转载自blog.csdn.net/qq_39993896/article/details/83351204