• 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. }  
  • 相关阅读:
    5月12日上课笔记-js 弹出框、函数、程序调试、基本事件、浏览器对象模型
    5月11日上课笔记-js简介
    5月9日上课笔记-网页定位、网页动画【HTML5】
    用IO字节流复制文件-CopyFileByIo
    5月8日上课笔记-浮动float
    5月5日上课笔记-盒子模型【HTML5】
    @RequestParam,@PathParam,@PathVariable,@QueryParam注解的使用区别
    vue-router 的配置
    VSCode自定义代码片段(模板)
    使用通用 Mapper 依据数据表生成实体类
  • 原文地址:https://www.cnblogs.com/xiao-wei-wei/p/3354690.html
Copyright © 2020-2023  润新知