【LeetCode】剑指 Offer 06. 从尾到头打印链表

【题目描述】

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

示例 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;
}

【解题思路】

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

原文地址:https://www.cnblogs.com/utank/p/13225485.html