uTank-木头
每一个你不满意的现在,都有一个你没有努力的曾经。

【题目描述】

输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。

示例 1:

输入:head = [1,3,2]
输出:[2,3,1]

限制:

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* reversePrint(struct ListNode* head, int* returnSize){
    int cnt = 0;
    int size = 0;
    int *out;
    struct ListNode *pre;
    struct ListNode *cur;
    struct ListNode *tmp;

    // 先反转链表并获得链表的长度
    pre = NULL;
    cur = head;
    while( cur != NULL )
    {
        tmp = cur->next;

        cur->next = pre;
        pre = cur;
        cur = tmp;
        size++;
    }

    out = (int *)malloc(sizeof(int) * size);
    while( pre != NULL )
    {
        *(out + cnt) = pre->val;
        pre = pre->next;
        cnt++;
    }

    *returnSize = size;

    return out;
}

 

【解题思路】

注:先反转链表,然后顺序输出反转后的链表数据;总的需要遍历链表两次;

 

posted on 2020-07-02 16:23  uTank  阅读(120)  评论(0编辑  收藏  举报