题目
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
输入:head = [1,3,2]
输出:[2,3,1]
方法一:遍历
首先,判断是否是空链表,如果是,就返回NULL;如果不是,获取目标链表的长度,然后从后往前遍历。
/**
* 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) {
//vector<int> result;
ListNode* end = head;
int length = 0;
//特殊情况:本身为空、本身就一个数
if(end == NULL){
vector<int> result(length,0);
return result;
}
while(end != NULL){
end = end->next;
length++;
}
vector<int> result(length,0);
for(int i = length-1;i >= 0;i--){
result[i] = head->val;
head = head->next;
}
return result;
}
};
方法二:栈
思路:定义一个栈,先把链表里的元素压入栈,然后再依次弹出到数组里。
class Solution {
public:
vector<int> reversePrint(ListNode* head){
vector<int> result;
stack<int> s;
if(head == NULL){
return result;
}
else{
while(head != NULL){
s.push(head->val);
head = head->next;
}
while(!s.empty()){
result.push_back(s.top());
s.pop();
}
return result;
}
}
};
方法三:递归
class Solution {
public:
void solution(vector<int> & res,ListNode* head){
if(head->next != NULL)
solution(res,head->next);
res.push_back(head->val);
}
vector<int> reversePrint(ListNode* head){
if(head == NULL) return {};
vector<int> result;
solution(result,head);
return result;
}
};
传引用 ,可以改变原来的值。