zl程序教程

您现在的位置是:首页 >  后端

当前栏目

剑指 Offer 06. 从尾到头打印链表(链表)

链表 打印 Offer 06 到头 从尾
2023-06-13 09:13:03 时间

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

示例 1:

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

限制:

0 <= 链表长度 <= 10000

题解 链表

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */
class Solution { 
   
public:
    vector<int> reversePrint(ListNode* head) { 
   
        ListNode * t = new ListNode(0,NULL);
        ListNode * h = t;
        while(head){ 
   
            ListNode * tt = head->next;
            head->next = t->next;
            t->next = head;
            head = tt;
        }
        vector<int>res;
        while(h->next){ 
   
            res.push_back(h->next->val);
            h = h->next;
        }
        return res;
    }
};

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/168645.html原文链接:https://javaforall.cn