1 題目描述
輸入一個鏈表的頭節點,從尾到頭反過來返回每個節點的值(用數組返回)。
2 思路
棧、遞歸、reverse
3 代碼
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> res;
vector<int> reversePrint(ListNode* head) {
//reverse
/*
while(head) {
res.push_back(head->val);
head = head->next;
}
//使用algorithm算法中的reverse反轉res
reverse(res.begin(), res.end());
return res;
*/
//棧
/*
stack<int> s;
//入棧
while(head) {
s.push(head->val);
head = head->next;
}
//出棧
while(!s.empty()) {
res.push_back(s.top());
s.pop();
}
return res;
*/
//遞歸
if(head == nullptr) {
return res;
}
reversePrint(head->next);
res.push_back(head->val);
return res;
}
};