输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。 【示例 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 |
原文:https://www.cnblogs.com/ziziQ/p/12510709.html