[6]从尾到头打印链表
1.题目
输入一个链表的头节点,从尾到头反过来打印出每个节点的值
2.思路
典型的后进先出,我们可以利用栈来实现这种顺序,每经过一个节点的时候,把该节点放到一个栈中
3.代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListReversingly(ListNode* head)
{
vector<int> res;
if(head==NULL) return {};
ListNode *cur = head;
while(cur != NULL)
{
res.push_back(cur->val);
cur = cur->next;
}
return vector<int>(res.rbegin(), res.rend()); // 数组反向输出
}
};