数据结构实验之链表一:顺序建立链表

时间:2019-02-14
本文章向大家介绍数据结构实验之链表一:顺序建立链表,主要包括数据结构实验之链表一:顺序建立链表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Problem Description

输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。

Input

第一行输入整数的个数N;
第二行依次输入每个整数。

Output

输出这组整数。

Sample Input

8
12 56 4 6 55 15 33 62

Sample Output

12 56 4 6 55 15 33 62

Hint

不得使用数组!

Source

 

//#include <iostream>
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;

typedef struct Node{
    int data;
    struct Node *next;
}list;

void creat(list * &L,int a){//建立链表(设置一个第三方链表用于做转换)
    list *s;
    list *now;
    L=(list *)malloc(sizeof(list));
    now = L;
    int d;
    for(int i=0;i<a;i++)
    {
        cin >> d;
        s = (list *)malloc(sizeof(list));
        s->data = d;
        now->next = s;
        now = s;
    }
    now->next = NULL;
}

void print(list * &L){
    list *p = L->next;
    while(p!=NULL)//防止出现空指针
    {
        if(p->next!=NULL)
            printf("%d ",p->data);
        else
            printf("%d\n",p->data);
        p = p->next;
    }
}
int main(){
    ios::sync_with_stdio(false);
    list *li;
    int a;
    cin >> a;
    creat(li,a);
    print(li);
    return 0;
}