wof168 2023-09-10 22:29 采纳率: 95.7%
浏览 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 length=1;
struct ListNode* pre=NULL;
struct ListNode* cur=head;
while(cur){
struct ListNode* next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
length++;
}
    int* arr=(int*)malloc(sizeof(int)*length);
for(int i=0;i<length;i++){
    if(pre==NULL){
        break;
    }
    arr[i]=pre->val;
    pre=pre->next;
}
return arr;
}
  • 写回答

2条回答 默认 最新

  • threenewbee 2023-09-10 22:31
    关注
    int* reversePrint(struct ListNode* head, int* returnSize) {
        int length = 0;
        struct ListNode* pre = NULL;
        struct ListNode* cur = head;
    
        while (cur) {
            struct ListNode* next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
            length++;
        }
    
        *returnSize = length;
        int* arr = (int*)malloc(sizeof(int) * (length - 1));
    
        for (int i = 0; i < length; i++) {
            if (pre == NULL) {
                break;
            }
            arr[i] = pre->val;
            pre = pre->next;
        }
    
        return arr;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月19日
  • 已采纳回答 9月11日
  • 创建了问题 9月10日