单链表复制


有一单链表,已知链表长为n,现在你觉得一个不够,想自己再复制一个,以防以后下次误删,记得要用链表!
 Input

输入有两行,第一行为整数n,直到n为0结束;第二行有n个数据。表长n不超过100。

Output

输出你Copy的那个链表,数据之间用空格分隔。


Sample Input

5
1 2 3 4 5
8
2 5 6 8 9 0 1 3
0
 Sample Output

1 2 3 4 5
2 5 6 8 9 0 1 3
 

#include<iostream>
#include<stdio.h>
#include<string.h>
using namespace std;

struct node {
    int data;
    node* next;
    node() {
        next=NULL;
    }
};

class List {
public:
    node* head;
    List() {
        head=new node;
        //   head->next=NULL;
    }
    void creat(int n) {
        node* r=head;
        int num;
        for(int i=0; i<n; i++) {
            cin>>num;
            //   if(num==0)break;
            node* s=new node;
            s->data=num;
            r->next=s;
            r=s;
        }
        r->next=NULL;
    }


    void Copy(node* copylist) {

        node* p=head->next;
        node* copyhead=copylist;
        while(p) {
            node* s=new node;
            s->data=p->data;
            copyhead->next=s;
            copyhead=s;
            p=p->next;
        }
        copyhead->next=NULL;

    }





    ~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 n;
    while(cin>>n&&n) {

        List list;
        list.creat(n);
        List copylist;
        list.Copy(copylist.head);
        copylist.print();

    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

haibianyoushark

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

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

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

打赏作者

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

抵扣说明:

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

余额充值