剑指 Offer 06. 从尾到头打印链表
思路一:翻转
1:用vector存从头到尾的每个节点值
2:返回时候用reverse翻转一下
时间复杂度:O(n)
空间复杂度:O(n)
/**
* 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> vec;
while(head!=nullptr){
vec.push_back(head->val);
head = head->next;
}
reverse(vec.begin(), vec.end());
return vec;
}
};
思路二:递归
/**
* 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) {
if(head==nullptr) return res;
reversePrint(head->next);//递归到最后一层
res.push_back(head->val);//开始从最后压入值到容器
return res;
}
};
思路三:使用辅助栈
/**
* 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) {
stack<ListNode*> stk;
vector<int> res;
while(head!=nullptr){
stk.push(head);
head = head->next;
}
while(!stk.empty()){
int tempnum = stk.top()->val;
stk.pop();
res.push_back(tempnum);
}
return res;
}
};