数组逆序重放(链表头插法练习)

本文介绍了一种使用链表实现数组逆序的方法,并提供了两种不同的C语言代码示例,一种是采用多余头结点的方式,另一种则直接进行操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门:http://ica.openjudge.cn/zz/1/

总时间限制: 1000ms  内存限制: 65536kB
描述
将一个数组中的值按逆序重新存放。例如,原来的顺序为8,6,5,4,1。要求改为1,4,5,6,8。
输入
输入为两行:第一行数组中元素的个数n(1<n<100),第二行是n个整数,每两个整数之间用空格分隔。
输出
输出为一行:输出逆序后数组的整数,每两个整数之间用空格分隔。
样例输入
5
8 6 5 4 1
样例输出
1 4 5 6 8

分析:头插法构造链表,然后扫描链表即可。

带多余头结点的代码:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 struct obj
 4 {
 5     int num;
 6     struct obj *next;
 7 };
 8 int main(int argc, char *argv[])
 9 {
10     int n,i,t;
11     struct obj *head=NULL,*temp,*p;
12     
13     head=(struct obj *)malloc(sizeof(struct obj));
14     head->next=NULL;
15     scanf("%d",&n);
16     for(i=0;i<n;i++)
17     {
18         scanf("%d",&t);
19         temp=(struct obj *)malloc(sizeof(struct obj));
20         temp->num=t;
21         temp->next=NULL;
22         
23         temp->next=head->next;
24         head->next=temp;
25     }
26     p=head->next;
27     while(p!=NULL)
28     {
29         printf("%d ",p->num);
30         p=p->next;
31     }/**/
32     printf("\n");
33     return 0;
34 }

 

不带多余头结点的代码:

 1 #include<stdio.h>
 2 #include<stdlib.h>
 3 struct obj
 4 {
 5     int num;
 6     struct obj *next;
 7 };
 8 int main(int argc, char *argv[])
 9 {
10     int n,i,t;
11     struct obj *head=NULL,*temp=NULL,*p=NULL;
12 
13     scanf("%d",&n);
14     for(i=0;i<n;i++)
15     {
16         scanf("%d",&t);
17         temp=(struct obj *)malloc(sizeof(struct obj));
18         temp->num=t;
19         temp->next=NULL;
20 
21         temp->next=head;
22         head=temp;
23     }
24 
25     p=head;
26     while(p!=NULL)
27     {
28         printf("%d ",p->num);
29         p=p->next;
30     }
31     printf("\n");
32     return 0;
33 }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值