输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}//初始化当前结点值为x,指针为空
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
vector<int> v;
for (ListNode *p = head; p != NULL; p = p->next)//NULL不是null
v.insert(v.begin(), p->val);//vector的头插法,从给定位置(v.begin())前面插入一个元素(p->val)
return v;
}
};
内存占用不大但是速度很慢考虑另一种方法,但是没时间先这样吧