1. 程式人生 > >9006:單鏈表的建立和遍歷

9006:單鏈表的建立和遍歷

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