zoukankan      html  css  js  c++  java
  • 九度oj题目1511:从尾到头打印链表

    题目1511:从尾到头打印链表

    时间限制:1 秒

    内存限制:128 兆

    特殊判题:

    提交:6010

    解决:1805

    题目描述:

    输入一个链表,从尾到头打印链表每个节点的值。

    输入:

    每个输入文件仅包含一组测试样例。
    每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。

    输出:

    对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。

    样例输入:
    1
    2
    3
    4
    5
    -1
    
    样例输出:
    5
    4
    3
    2
    1

    参考代码:

    递归做法。

     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<stdlib.h>
     4 #include<stack>
     5 using namespace std;
     6 typedef struct node{
     7     int val;
     8     node *next;
     9 }node;
    10 void print_link(const node *tmp_node){
    11     if(tmp_node->next!=NULL)
    12         print_link(tmp_node->next);
    13     printf("%d
    ",tmp_node->val);
    14 }
    15 int main()
    16 {
    17     //freopen("D:\INPUT.txt","r",stdin);
    18     int tmp;
    19     node *head=new node;
    20     head->next=NULL;
    21     node *pre_node=head;
    22     while(scanf("%d",&tmp)&&tmp>0){
    23         node *tmp_node=new node;
    24         tmp_node->val=tmp;
    25         tmp_node->next=NULL;
    26 
    27         pre_node->next=tmp_node;
    28         pre_node=tmp_node;
    29     }
    30     print_link(head->next);
    31     return 0;
    32 }

    自己的代码:

     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<stdlib.h>
     4 #include<stack>
     5 using namespace std;
     6 struct node{
     7     int v;
     8     node *next;
     9 };
    10 void print(node *p){
    11     if(p->next){//attention!!
    12         print(p->next);
    13     }
    14     cout<<p->v<<endl;
    15 }
    16 int main()
    17 {
    18     //freopen("D:\INPUT.txt","r",stdin);
    19     int n;
    20     node *head=new node();
    21     head->next=NULL;
    22     node *p,*q=head;
    23     while(scanf("%d",&n)&&n!=-1){
    24         p=new node();
    25         p->v=n;
    26         p->next=NULL;
    27         q->next=p;
    28         q=p;
    29     }
    30     print(head->next);
    31     return 0;
    32 }
  • 相关阅读:
    Android SDK、NDK、JNI的简单介绍
    深入理解计算机系统—异常
    Jmeter3.1 使用及新增报告功能
    jmeter3.1连接数据库报错,ORA00923: 未找到要求的 FROM 关键字
    Jenkins插件、war下载地址
    jenkins自动打tag
    jenkins参数化构建过程
    Jmeter接口测试自动化(jmeter+ant+jenkins持续集成)
    既然选择开始就不会停下
    知识提升整体
  • 原文地址:https://www.cnblogs.com/Deribs4/p/4649862.html
Copyright © 2011-2022 走看看