zoukankan      html  css  js  c++  java
  • 数组逆序重放(链表头插法练习)

    传送门: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("
    ");
    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("
    ");
    32     return 0;
    33 }
  • 相关阅读:
    iOS设计模式之一:MVC模式和单例模式
    高清图标搜索引擎
    中国地址英文书写格式(转载)
    iOS设置状态栏样式,statusBarStyle
    关于iOS启动页launchImage和各个屏幕使用的分辨率
    使用终端命令行将本地项目上传到Github
    iOS项目梳理-第一天- 项目框架搭建
    静态库合成
    iOS中的通知
    iOS UserSize Classes
  • 原文地址:https://www.cnblogs.com/huashanqingzhu/p/7243838.html
Copyright © 2011-2022 走看看