-
题目描述:
-
输入一个链表,从尾到头打印链表每个节点的值。
-
输入:
-
每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。
-
输出:
-
对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。
-
样例输入:
-
1 2 3 4 5 -1
-
样例输出:
-
5 4 3 2 1
推荐指数:※
来源:http://ac.jobdu.com/problem.php?pid=1511
1.直接使用栈
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<stack> using namespace std; int main() { int tmp; stack<int>st; while(scanf("%d",&tmp)&&tmp>0){ st.push(tmp); } while(!st.empty()){ printf("%d\n",st.top()); st.pop(); } return 0; }
2.递归打印
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<stack> using namespace std; typedef struct node{ int val; node *next; }node; void print_link(const node *tmp_node){ if(tmp_node->next!=NULL) print_link(tmp_node->next); printf("%d\n",tmp_node->val); } int main() { int tmp; node *head=new node; head->next=NULL; node *pre_node=head; while(scanf("%d",&tmp)&&tmp>0){ node *tmp_node=new node; tmp_node->val=tmp; tmp_node->next=NULL; pre_node->next=tmp_node; pre_node=tmp_node; } print_link(head->next); return 0; }