acwing 17. 从尾到头打印链表

题目地址 https://www.acwing.com/problem/content/description/18/

来源:剑指Offer

 

输入一个链表的头结点,按照 从尾到头 的顺序返回节点的值。

返回的结果用数组存储。

样例

输入:[2, 3, 5]
返回:[5, 3, 2]

 

题解:

将链表转换成vector  其实大量链表题目 如果允许的话  都可以转化成链表做 比较便利

代码

/**
 * 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) {
        ListNode* p =head;
        vector<int> v;
        while(p != NULL){
            v.push_back(p->val);    
            p= p->next;
        }
        reverse(v.begin(),v.end());
        return v;
    }
};

 

posted on 2019-07-17 21:39  itdef  阅读(138)  评论(0编辑  收藏  举报

导航