Description
输入整数个数N,再输入N个整数,按照这些整数输入的相反顺序建立单链表,并依次遍历输出单链表的数据。
Input
第一行输入整数N;;
第二行依次输入N个整数,逆序建立单链表。
Output
依次输出单链表所存放的数据。
Sample
Input
10
11 3 5 27 9 12 43 16 84 22
Output
22 84 16 43 12 9 27 5 3 11
Hint
不能使用数组!
对你有帮助的话点个赞给点鼓励哦🌹🌹🌹🌹🌹🌹👏👏👏👏👀👀👀
#include <stdio.h>
#include <stdlib.h>
struct node//定义链表类型
{
int data;//数据域
struct node *next;//指针域
};
struct node *creatrev(int n);//逆序建立链表函数。返回指针值
void display(struct node *head);//显示链表中结点值
int main()
{
int n;//结点个数
struct node *head;//定义链表头指针
scanf("%d",&n);//读入结点个数
head=creatrev(n);//调用逆序建立表函数,返回值赋给 head
display(head);//显示链表中结点值
return 0;
}
struct node *creatrev(int n)
{
struct node *head,*p;//头指针和游动指针
int i;
head=(struct node*)malloc(sizeof(struct node));//初始化头结点 head,分配空间
head->next=NULL;//next域置NULL
for(i=0;i<n;i++)//循环建立新结点 p。并插入到头结点 head后面
{
p=(struct node*)malloc(sizeof(struct node));//为新结点分配存储空间
scanf("%d",&p->data);//读入数据,赋值给新结点数据域
p->next=head->next;//让新结点指针域指向原来头结点后面的结点
head->next=p;//让结点 next 域指向新结点 p
}
return head;//返回头结点
};
void display(struct node *head)
{
struct node *p;//定义游动指针
p=head->next;//让 p 指向第一个结点
while(p!=NULL)//当 P 为空时退出循环
{
if(p->next==NULL)//如果已经是最后一个结点,输出值后换行
printf("%d\n",p->data);
else
printf("%d ",p->data);//否则输出空格
p=p->next;//p 指向下一个结点
}
}
对你有帮助的话点个赞给点鼓励哦🌹🌹🌹🌹🌹🌹👏👏👏👏👀👀👀
注:老师最近教的 嘿嘿