剑指offer-03-从尾到头打印链表

2018-08-06  本文已影响0人  Buyun0

从尾到头打印链表:

输入一个链表,按链表值从尾到头的顺序返回一个ArrayList。

思路:没啥说的,新建一个数组依次复制链表各个节点的值,然后用reverse函数反转数组。

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> s;
        if(head == NULL){
            return s;
        }
        
        
        while(true){
            s.push_back(head->val);
            if(head->next == NULL)break;
            head = head->next;
        }
        
        reverse(s.begin(),s.end());
        
        
        return s;
    }
};
上一篇 下一篇

猜你喜欢

热点阅读