劍指offer 5. 從尾到頭列印連結串列
阿新 • • 發佈:2019-01-04
輸入一個連結串列的頭結點,按照 從尾到頭 的順序返回節點的值。
返回的結果用陣列儲存。
樣例
輸入:[2, 3, 5]
返回:[5, 3, 2]
返回逆序可以對原陣列逆序 reverse(res.begin(), res.end())
也可以直接構造一個逆序陣列 vector<int>(res.rbegin(), res.rend())
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head) {
vector<int>res;
while(head){
res.push_back(head -> val);
head = head -> next;
}
return vector<int>(res.rbegin(), res.rend());
}
};