这个和反转链表不一样,一般用作显示的功能最好不要改变链表结构。
利用栈:
/**
* 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 = {};
stack<ListNode*> s;
ListNode * node =head;
while(node!=NULL)
{
s.push(node);
node = node->next;
}
while(!s.empty())
{
vec.push_back(s.top()->val);
s.pop();
}
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> reversePrint(ListNode* head) {
vector<int> a = {};
if(head!=nullptr)
{
if(head->next != nullptr)
{
a = reversePrint(head->next);
}
a.push_back(head->val);
}
return a;
}
};