版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39993896/article/details/83351484
有一单链表,已知链表长为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;
}