个人免费网站申请,北京网校,宁波seo外包推广软件,html个人博客完整代码文章目录1. 题目2. 解题2.1 stack解题2.2 递归2.3 反转链表1. 题目
输入一个链表的头节点#xff0c;从尾到头反过来返回每个节点的值#xff08;用数组返回#xff09;。
示例 1#xff1a;
输入#xff1a;head [1,3,2]
输出#xff1a;[2,3,1]限制#xff1a;
0 从尾到头反过来返回每个节点的值用数组返回。
示例 1
输入head [1,3,2]
输出[2,3,1]限制
0 链表长度 10000来源力扣LeetCode 链接https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof 著作权归领扣网络所有。商业转载请联系官方授权非商业转载请注明出处。
2. 解题
2.1 stack解题
class Solution {
public:vectorint reversePrint(ListNode* head) {stackint s;while(head){s.push(head-val);head head-next;}vectorint ans;while(!s.empty()){ans.push_back(s.top());s.pop();}return ans;}
};2.2 递归
class Solution {vectorint ans;
public:vectorint reversePrint(ListNode* head) {dfs(head);return ans;}void dfs(ListNode* head){if(!head)return;dfs(head-next);ans.push_back(head-val);}
};2.3 反转链表
class Solution {vectorint ans;
public:vectorint reversePrint(ListNode* head) {if(!head)return {};head reverseList(head);while(head){ans.push_back(head-val);head head-next;}return ans;}ListNode* reverseList(ListNode* head){ //反转链表返回新表头ListNode *prev NULL, *nt head-next;while(head head-next){head-next prev;prev head;head nt;nt nt-next;}head-next prev;return head;}
};