zoukankan      html  css  js  c++  java
  • 1511 从尾到头打印链表

    题目描述:

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

     

    输入:

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

     

    输出:

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

     

    样例输入:
    1
    2
    3
    4
    5
    -1
    
    样例输出:
    5
    4
    3
    2
    1
    推荐指数:※
    来源:http://ac.jobdu.com/problem.php?pid=1511
    1.直接使用栈
    1. #include<iostream>  
    2. #include<stdio.h>  
    3. #include<stdlib.h>  
    4. #include<stack>  
    5. using namespace std;  
    6. int main()  
    7. {  
    8.     int tmp;  
    9.     stack<int>st;  
    10.     while(scanf("%d",&tmp)&&tmp>0){  
    11.         st.push(tmp);  
    12.     }  
    13.     while(!st.empty()){  
    14.         printf("%d ",st.top());  
    15.         st.pop();  
    16.     }  
    17.     return 0;  
    18. }  

    2.递归打印
    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.     int tmp;  
    18.     node *head=new node;  
    19.     head->next=NULL;  
    20.     node *pre_node=head;  
    21.     while(scanf("%d",&tmp)&&tmp>0){  
    22.         node *tmp_node=new node;  
    23.         tmp_node->val=tmp;  
    24.         tmp_node->next=NULL;  
    25.   
    26.         pre_node->next=tmp_node;  
    27.         pre_node=tmp_node;  
    28.     }  
    29.     print_link(head->next);  
    30.     return 0;  
    31. }  
  • 相关阅读:
    简单的倒计时 时间显示
    git submodule
    使用选择器语法来查找元素
    yo bootstrap mui 使用对比
    flexbox 兼容安卓4.3
    mac 下 php 安装 中的坑
    微信网页开发
    能发送http请求(get,post)的工具
    h5宣传页制作过程中遇到的问题
    功能模块图、业务流程图、处理流程图、ER图,数据库表图(概念模型和物理模型)画法
  • 原文地址:https://www.cnblogs.com/xiao-wei-wei/p/3354690.html
Copyright © 2011-2022 走看看