leetcode---LCR 123.图书整理1

书店店员有一张链表形式的书单,每个节点代表一本书,节点中的值表示书的编号。为更方便整理书架,店员需要将书单倒过来排列,就可以从最后一本书开始整理,逐一将书放回到书架上。请倒序返回这个书单链表。

示例 1:

输入:head = [3,6,4,1]

输出:[1,4,6,3]

提示:

0 <= 链表长度 <= 10000

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
 
int* reverseBookList(struct ListNode* head, int* returnSize) {
    struct ListNode*p=head;
    int count=0;
    while(p!=NULL)
    {
        count++;//遍历得到链表的结点数
        p=p->next;
    }
    *returnSize=count;
    int *q=(int *)malloc(count*sizeof(int));
    int i=count-1;
    p=head;
    while(p!=NULL)
    {
        q[i--]=p->val;//将倒叙链表元素存入数组
        p=p->next;
    }
    return q;
}

leetcode---LCR 123.图书整理1_第1张图片

你可能感兴趣的:(leetcode,算法,职场和发展)