🏆个人主页:企鹅不叫的博客
🌈专栏
⭐️ 博主码云gitee链接:代码仓库地址
⚡若有帮助可以【关注+点赞+收藏】,大家一起进步!
💎一、题目
🏆1.题目描述
🏆2.原题链接
💎二、解题报告
🏆1.思路分析
🔑思路1:
首先遍历一遍链表得到链表的长度,然后再遍历一遍链表,将所有值从数组最后向前依次存放
🔑思路2:
用vector接收链表,逆置输出
🔑思路3:
递归输出
🏆2.时间复杂度
🧡O(N)
🏆3.代码详解
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* reversePrint(struct ListNode* head, int* returnSize){
int count = 0;
struct ListNode* cur = head;
while(cur){ //1
cur = cur->next;
count++;
}
int* arr = (int*)malloc(sizeof(int)*count);
*returnSize = count;
while(head){
arr[count-1] = head->val; //2
head = head->next;
count--;
}
return arr;
}
--------------------------------------------------
//递归
class Solution {
public:
void reversePrintcore(vector<int>& v, ListNode* head)
{
if(head == nullptr) return;
reversePrintcore(v, head->next);//将下一个节点递归
v.push_back(head->val);//返回的时候将节点值差入
}
vector<int> reversePrint(ListNode* head) {
vector<int> v;
reversePrintcore(v, head);
return v;
}
};
1.遍历链表得到长度
2.遍历链表将数据存放到数组当中