剑指Offer:从尾到头的打印链表
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof
题目:输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
示例 1:
输入:head = [1,3,2]
输出:[2,3,1]
限制:
0 <= 链表长度 <= 10000
题解:利用栈的先进后出的特性,从头开始扫描链表,同时将链表中的数据存入到栈中,全部存完之后,再进行出栈,实现倒序。
/**
* 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<int> s;
vector<int> result;
ListNode* pre = head;
while(pre){
s.push(pre->val);
pre = pre->next;
}
while(!s.empty()){
result.push_back(s.top());
s.pop();
}
return result;
}
};