输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2] 输出:[2,3,1]
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int getListNodeLength(struct ListNode* head){
int len = 0;
struct ListNode* p = head;
while(p!=NULL){
len++;
p = p->next;
}
return len;
}
int* reversePrint(struct ListNode* head, int* returnSize){
if(head==NULL){
*returnSize = 0;
return NULL;
}
struct ListNode *P,*C,*N; //反转链表开始
P = NULL;
C = head;
while(C!=NULL){
N =C->next; //N的必要性
C->next = P;
P= C;
C = N;
} //反转链表结束
int length = getListNodeLength(P);
int *arr = (int *)malloc(length * sizeof(int));
int i;
for(i=0;i<length;i++){
arr[i] = P->val;
P = P->next;
}
* returnSize = length;
return arr;
重点是反转链表,之后求的链表长度申请数组,然后遍历数组一一对应填入。