/* 输入一个链表,从尾到头打印链表每个节点的值。 */ #include <iostream> #include <vector> using std::cout; using std::endl; using std::vector; struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; class Solution { public: vector<int> printListFromTailToHead(ListNode* head) { vector<int> vec_1; vector<int> vec_2; ListNode *pCurrent = head; while (pCurrent != NULL){ vec_1.push_back(pCurrent->val); pCurrent = pCurrent->next; } while (!vec_1.empty()){ vec_2.push_back(vec_1.back()); vec_1.pop_back(); } return vec_2; } }; void foo() { ListNode l1(67); ListNode l2(0); ListNode l3(33); ListNode l4(6); l1.next = &l2; l2.next = &l3; l3.next = &l4; Solution sol; sol.printListFromTailToHead(&l1); } int main() { foo(); return EXIT_SUCCESS; }
原文地址:http://siliconmaigc.blog.51cto.com/12904785/1926422