标签:eve node for struct turned size dao return returns
题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 9 /** 10 * Note: The returned array must be malloced, assume caller calls free(). 11 */ 12 int* reversePrint(struct ListNode* head, int* returnSize){ 13 if(head==NULL){ 14 *returnSize=0; 15 return NULL; 16 } 17 int i,j,len=0; 18 struct ListNode *q=head; 19 while(q){ 20 len++; 21 q=q->next; 22 } 23 *returnSize=len; 24 int *a=(int *)malloc(sizeof(int)*len); 25 q=head; 26 i=0; 27 while(q){ 28 a[i++]=q->val; 29 q=q->next; 30 } 31 for(i=0;i<len/2;i++){ 32 int tmp=a[i]; 33 a[i]=a[len-i-1]; 34 a[len-i-1]=tmp; 35 } 36 return a; 37 }
另一种是链表先逆序:
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * struct ListNode *next; 6 * }; 7 */ 8 9 /** 10 * Note: The returned array must be malloced, assume caller calls free(). 11 */ 12 int* reversePrint(struct ListNode* head, int* returnSize){ 13 if(head==NULL){ 14 *returnSize=0; 15 return NULL; 16 } 17 struct ListNode *pre=NULL,*cur=head,*tmp; 18 while(cur){ 19 tmp=cur->next; 20 cur->next=pre; 21 pre=cur; 22 cur=tmp; 23 } 24 int i=0,len=0; 25 struct ListNode *q=pre; 26 while(q){ 27 len++; 28 q=q->next; 29 } 30 *returnSize=len; 31 int *a=(int *)malloc(sizeof(int)*len); 32 q=pre; 33 while(q){ 34 a[i++]=q->val; 35 q=q->next; 36 } 37 return a; 38 }
标签:eve node for struct turned size dao return returns
原文地址:https://www.cnblogs.com/shixinzei/p/12405507.html