输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
输入:head = [1,3,2]
输出:[2,3,1]
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if (!head)
return {};
vector<int> res;
ListNode* node = head;
stack<int> s;
while (node->next) {
s.push(node->val);
node = node->next;
}
s.push(node->val);
while (!s.empty()) {
res.push_back(s.top());
s.pop();
}
return res;
}
};
遍历链表,将对应值依次压入栈。再将栈中数据依次pop到结果数组中。
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
if (!head)
return {};
vector<int> res = reversePrint(head->next);
res.push_back(head->val);
return res;
}
};
栈可以压入数字结果,同样也可以压入函数,后者即为递归做法。使用递归代码会更加简洁,但是要注意当链表很长时可能导致函数调用栈溢出。
原文:https://www.cnblogs.com/tmpUser/p/14401747.html