题目描述
输入一个链表,从尾到头打印链表每个节点的值。
思路
1:可以用一个栈把结点挨个进栈在出栈打印
2:可以用递归的方法:如果当前结点的下一个结点不同则处理下一个结点;为空,则输出当前结点并返回;
code:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int>output;
if(head==nullptr){
cout<<"链表为空"<<endl;
return output;
}
stack<ListNode*>s;
ListNode *now_node=head;
while(now_node!=nullptr){
s.push(now_node);
now_node=now_node->next;
}
while(!s.empty()){
now_node=s.top();
s.pop();
output.push_back(now_node->val);
}
return output;
}
};
void printListFromTailToHead(ListNode* head){
if(head==nullptr)
return;
if(head->next!=nullptr){
printListFromTailToHead(head-next);
}else{
cout<<head.val;
return ;
}