-
题目描述:
-
输入一个链表,从尾到头打印链表每个节点的值。
-
输入:
-
每个输入文件仅包含一组测试样例。
每一组测试案例包含多行,每行一个大于0的整数,代表一个链表的节点。第一行是链表第一个节点的值,依次类推。当输入到-1时代表链表输入完毕。-1本身不属于链表。
-
输出:
-
对应每个测试案例,以从尾到头的顺序输出链表每个节点的值,每个值占一行。
-
样例输入:
-
1 2 3 4 5 -1
-
样例输出:
-
5 4 3 2 1
思路,尾递归打印~
#include <iostream> #include <fstream> #include <vector> #include <cstdio> using namespace std; /* 题目1511:从尾到头打印链表 */ typedef struct node { int val; node * next; node (int val) : val(val), next (0) {} } * p_node; p_node create_list (p_node list, const vector<int> & arr) { if ( arr.empty ()) return NULL; list = new node (arr.at(0)); p_node pre = list ; for (int i = 1, sz = arr.size(); i < sz; ++i ) { p_node p = new node (arr.at(i)); pre->next = p; pre = p; } return list; } void print (p_node list) { if (NULL == list) return; p_node p = list; while (p) { cout << "node : " << p->val << endl; p = p->next; } } void im_print(p_node p) { if (p) { im_print(p->next); printf("%d\n",p->val); } } void del_node (p_node list) { if (NULL == list) return; p_node p = NULL; while (list) { p = list->next; //cout << "del node : " << list->val << endl; delete list; list = p; } list = NULL; } int main () { int t; vector<int> v; while (scanf("%d", &t) == 1 && t != -1 ) v.push_back(t); p_node head = create_list(head, v); //print(head); im_print(head); del_node(head); }