从尾到头打印链表

题目描述

输入一个链表,从尾到头打印链表每个节点的值。

代码

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> ans;
        ListNode* cur = head;
        while (cur != NULL) {
            ans.push_back(cur->val);
            cur = cur->next;
        }
        int temp;
        for (int i= 0, j = ans.size() - 1; i < j; ++i, --j) {
            temp = ans[i];
            ans[i] = ans[j];
            ans[j] = temp;
        }
        return ans;
    }
};
原文地址:https://www.cnblogs.com/jecyhw/p/6535768.html