解决思路:反向输出链表内容其方式是先遍历到的节点后输出,典型的先进后出,使用辅助栈来完成,先把遍历到的节点放入栈中,最后一一出栈访问元素即可。于是得到如下代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
stack<int > a;
vector<int > ans;
vector<int> reversePrint(ListNode* head) {
ListNode* node = head;
vector<int > ans;
while(node!=nullptr){
a.push(node->val);
node = node->next;
}
while(!a.empty()){
ans.push_back(a.top());
a.pop();
}
return ans;
}
};
用栈来做的题目大多可以用递归得到,所以有出现了如下写法:
class Solution {
public:
vector<int > ans;
vector<int> reversePrint(ListNode* head) {
if(head!=nullptr){
if(head->next!=nullptr){
reversePrint(head->next);
}
ans.push_back(head->val);
}
return ans;
}
};
上面都是在链表顺序不发生改变情况下写出的,如果可以更改链表的顺序可以直接更改后输出,有:
class Solution {
public:
vector<int > ans;
vector<int> reversePrint(ListNode* head) {
ListNode* pPrev = nullptr;
ListNode* pNode = head;
ListNode* ReverseHead = nullptr; //保存翻转后的头节点
while(pNode!=nullptr){
ListNode* pNext = pNode->next;
if(pNext==nullptr)
ReverseHead = pNode;
pNode->next = pPrev;
pPrev = pNode;
pNode = pNext;
}
pNode = ReverseHead;
while(pNode!=nullptr){
ans.push_back(pNode->val);
pNode = pNode->next;
}
return ans;
}
};