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\n",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\n",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. }  
posted @ 2013-10-06 21:44  小薇林  阅读(312)  评论(2编辑  收藏  举报