首页 > 编程语言 > 详细

【剑指offer】算法题06.从尾到头打印链表(C++)

时间:2020-03-17 15:45:40      阅读:42      评论:0      收藏:0      [点我收藏+]
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

【示例 1】
输入:head = [1,3,2]
输出:[2,3,1]
 
【限制】
0 <= 链表长度 <= 10000

【解题思路】

思路一:从头开始遍历链表,每一次都将节点的值插入到数组的第一个位置。插入时使用emplace()或者insert()都可以。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> nums;
        if(head==NULL) 
            return nums;
        ListNode* p=head;
        while(p!=NULL){
            nums.emplace(nums.begin(),p->val);
            //nuns.insert(nuns.begin(),p->Val);
            p=p->next;
        }
        return nums;
    }
};

思路二:从头遍历链表,将节点值按顺序存入数组中,最后将数组倒序。利用reverse()。

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    vector<int> reversePrint(ListNode* head) {
        vector<int> nums;
        if(head==NULL) 
            return nums;
        ListNode* p=head;
        while(p!=NULL){
            nums.push_back(p->val);
            p=p->next;
        }
        reverse(nums.begin(),nums.end());
        return nums;
    }
};

【结果对比】

思路 执行时间 内存消耗
72ms 10.1MB
4ms 10.3MB

【剑指offer】算法题06.从尾到头打印链表(C++)

原文:https://www.cnblogs.com/ziziQ/p/12510709.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!