版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39993896/article/details/83351314
Problem Description
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
Input
输入数据有多组,每组数据占两行;每组第一行为一个数字N(0<N<=50);第二行有N个整数。
Output
每组输出占一行,输出这组整数,每两个数字之间用一个空格分隔。
Sample Input
5 12 32 45 78 54
Sample Output
12 32 45 78 54
#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;
}
~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){
List list;
list.creat(n);
list.print();
}
return 0;
}