这是剑指offer上的题。首先要弄明白链表的头和尾。单向链表只能从头开始查找。最简单的做法,就是将链表中的元素从头读到尾,存到vector中。然后利用reverse函数反转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> list; while(head != NULL) { list.push_back(head->val); head = head->next; } reverse(list.begin(),list.end()); //reverse()函