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

从尾到头打印链表

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

/**
*  struct ListNode {
*        int val;
*        struct ListNode *next;
*        ListNode(int x) :
*              val(x), next(NULL) {
*        }
*  };
*/
#include <cstddef>
class Solution {
public:
    vector<int> printListFromTailToHead(ListNode* head) {
        vector<int> arr;
        ListNode* cur = head;
        ListNode* next = NULL;
        ListNode* L = (ListNode*)malloc(sizeof(ListNode));
        L -> val = -1;
        L -> next = NULL;
        // 逆置链表
        while(cur != NULL) {
            next = cur -> next;
            cur -> next = L ->next;
            L -> next = cur;
            cur = next;
        }
        next = L;
        while(next -> next != NULL) {
            next = next -> next;
            arr.push_back(next -> val);
        }
        return arr;
    }
};

全部评论

相关推荐

2025-12-25 16:26
已编辑
河北科技学院 Java
勇敢的牛油不服输:2800-300那不等于2500一个月吗兄弟们
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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