[AcWing 17] 从尾到头打印链表

image


点击查看代码
/**
 * 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;
        }
        reverse(res.begin(), res.end());
        return res;
    }
};

  1. 把链表复制到 vector 中,使用 reverse 函数进行翻转
posted @ 2022-04-23 17:44  wKingYu  阅读(24)  评论(0)    收藏  举报