题目描述
输入N个整数,按照输入的顺序建立单链表存储,并遍历所建立的单链表,输出这些数据。
输入
第一行输入整数的个数N;
第二行依次输入每个整数。
输出
输出这组整数。
示例输入
8
12 56 4 6 55 15 33 62
示例输出
12 56 4 6 55 15 33 62
参考代码:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next; } ;
struct node *create (int n) //建链表
{
int i; struct node *h,*t,*p;
h=(struct node *)malloc(sizeof (struct node )); //申请头结点
h->next=NULL;
t=h; //头尾指针指向同一个点
for (i=1;i<=n;i++) //建立n个点的链表
{
p=(struct node *)malloc(sizeof (struct node)); //申请新结点
scanf ("%d",&p->data); //输入每个结点的数据
p->next=NULL; //结点的指针域为空
t->next=p; //将新结点插入链表尾部
t=p; //让链表的尾结点指向新结点
}
return (h);
}
void print (struct node *h) //输出链表中的数据
{
struct node *p;
p=h->next;
while (p!=NULL)
{
printf ("%d",p->data);
if (p->next !=NULL) printf (" ");
p=p->next; //p指向下一个结点
}
printf ("\n");
}
int main()
{
int n;
struct node *h;
scanf ("%d",&n); //输入结点的个数
h=create(n); //建立链表
print (h); //输出链表
return 0;
}