题目描述
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
思考与代码
题目中有要求,Note: The returned array must be malloced, assume caller calls free().这个数组需要这样建立。
这是自己想的:先反转链表,然后存进数组res[ ]中,最后返回数组要这样写返回数组return res;
。
/**
* 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){
struct ListNode *prev=NULL;
struct ListNode *curr=head;
int length=0;
while(curr){
length++;
struct ListNode *next=curr->next;//直接执行了
curr->next=prev;
prev=curr;
curr=next;
}
//int* returnSize这个就是想返回一下长度,传过来的是随意的变量名称,而不是数,这里是让我自己返回一个数
*returnSize=length;
//题目中有要求,这个数组需要这样建立
int *res=malloc(length*sizeof(int));
for(int i=0;i<length;i++){
res[i]=prev->val;
prev=prev->next;
}
return res;
}
大佬的想法:
第一种方法:
先遍历获取长度,然后创建和长度大小一样数组,然后将链表的第一个元素插入数组的最后一个位置,链表的第二个元素插到数组的倒数第二个位置,依次类推。
/**
* 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 len = 0;
struct ListNode* lt = head;
while(lt!=NULL)
{
len++;
lt = lt->next;
}
*returnSize = len;
//开辟大小为len的数组
int *arr = (int *)malloc(len*sizeof(int));
while(head!=NULL)
{
arr[len-1] = head->val;
head = head->next;
len--;
}
return arr;
}
第二个大佬的四种方法:
C++太妙了,直接自带push,pop等方法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode* head) {
//方法1:reverse反转法
/*
while(head){
res.push_back(head->val);
head = head->next;
}
//使用algorithm算法中的reverse反转res
reverse(res.begin(),res.end());
return res;
*/
//方法2:入栈法
/*
stack<int> s;
//入栈
while(head){
s.push(head->val);
head = head->next;
}
//出栈
while(!s.empty()){
res.push_back(s.top());
s.pop();
}
return res;
*/
//方法3:递归
/*
if(head == nullptr)
return res;
reversePrint(head->next);
res.push_back(head->val);
return res;
*/
//方法4:改变链表结构
ListNode *pre = nullptr;
ListNode *next = head;
ListNode *cur = head;
while(cur){
next = cur->next;//保存当前结点的下一个节点
cur->next = pre;//当前结点指向前一个节点,反向改变指针
pre = cur;//更新前一个节点
cur = next;//更新当前结点
}
while(pre){//上一个while循环结束后,pre指向新的链表头
res.push_back(pre->val);
pre = pre->next;
}
return res;
}
};