文章目录
- 1. 题目
- 2. 解题
- 2.1 stack解题
- 2.2 递归
- 2.3 反转链表
1. 题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 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:vector<int> reversePrint(ListNode* head) {stack<int> s;while(head){s.push(head->val);head = head->next;}vector<int> ans;while(!s.empty()){ans.push_back(s.top());s.pop();}return ans;}
};
2.2 递归
class Solution {vector<int> ans;
public:vector<int> 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 {vector<int> ans;
public:vector<int> 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;}
};