N03、从尾到头打印链表(挺简单的)

3、从尾到头打印链表

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

{
     67,0,24,58}

返回值

[58,24,0,67]
1、这题也太简单了,从前向后保存,然后reverse不就可以了吗。。。

运行时间:3ms 占用内存:504k

    vector<int> printListFromTailToHead(ListNode* head) {
     
        if( head == nullptr) return vector<int>();
        
        vector<int> result;
        while(head != nullptr){
     
            result.push_back(head->val);
            head = head->next;
        }
        
        reverse(result.begin(),result.end());
        return result;
        
    }
2、不用reverse,返回一个逆序也行

运行时间:2ms 占用内存:480k

    vector<int> printListFromTailToHead(ListNode* head) {
     
        if( head == nullptr) return vector<int>();
        
        vector<int> result;
        while(head != nullptr){
     
            result.push_back(head->val);
            head = head->next;
        }
        
       // reverse(result.begin(),result.end());
        return vector<int>(result.rbegin(),result.rend());
        
    }

美女帅哥们如果觉得写的还行,有点用的话麻烦点个赞或者留个言支持一下阿秀~
如果觉得狗屁不通,直接留言开喷就完事了。

需要该笔记PDF版本的去个人公众号【拓跋阿秀】下回复“阿秀剑指offer笔记”即可。

你可能感兴趣的:(原创,算法,c++,c语言)