题解 | #从尾到头打印链表#

从尾到头打印链表

https://www.nowcoder.com/practice/d0267f7f55b3412ba93bd35cfa8e8035

两次遍历,一次统计长度,一次逆序输出。

int* printListFromTailToHead(struct ListNode* listNode, int* returnSize ) {
    int *res;
    struct ListNode* tmp = listNode;
    int n = 0;
    while (tmp) {
        n++;
        tmp = tmp->next;
    }
    printf("%i", n);
    *returnSize = n;
    res = (int*)malloc(sizeof(int) * n);
    for (int i = n - 1; i >= 0; i--) {
        res[i] = listNode->val;
        // printf("%i", listNode->val);
        listNode = listNode->next;
    }
    return res;
    // write code here
}

全部评论

相关推荐

龙珠传说:nb,公务员解约不需要支付违约金吧
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务