输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。

输入格式:

第一行输入整数N(1<=N<=100000)。

第二行依次输入N个整数,逆序建立单链表。

输出格式:

依次输出单链表所存放的数据。

输入样例:

10
11 3 5 27 9 12 43 16 84 22

输出样例:

22 84 16 43 12 9 27 5 3 11

 

#include <stdio.h>
#include <stdlib.h>
struct node//创建结点类型
{
    int data;
    struct node*next;
};
struct node*creat(int n)//用函数生成长度为n的链表
{
    struct node *head,*p;
    head=(struct node *)malloc(sizeof(struct node));//为头结点动态分配空间,打好木桩
    head->next=NULL;//为头结点指针域初始化
    for(int i=1;i<=n;i++)//在头结点后面插入n个新结点
    {
        p=(struct node*)malloc(sizeof(struct node));//为新结点p动态分配空间
        p->next=head->next;//为p结点指针域定好指向
        scanf("%d",&p->data);//初始化p结点数据域
        head->next=p;
    }
    return head;
}
void output (struct node*p)
{
    struct node*i;
    for(i=p;i!=NULL;i=i->next)
    {
        printf("%d",i->data);
        if(i->next != NULL) printf(" ");//注意格式的控制
        else printf("\n");
    }
}
int main()
{
    int n;
    scanf("%d",&n);//输入
    struct node*head;
    head=creat(n);//输入+处理
    output(head->next);//输出

    return 0;
}

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐