题目描述
输入一个链表,从尾到头打印链表每个节点的值
思路:第一个遍历到的结点最后一个输出,而最后一个遍历到的结点第一个输出。典型的“后进先出”,我们可以使用栈来实现这种顺序。
每经过一个结点的时候,把该结点放到栈中。当遍历完整个链表后,再从栈顶开始逐个输出结点的值,此时输出的结点的顺序已经反转过来了。
实现:C++
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
if (head == NULL){
return vector<int>();
}
vector<int> res;
stack<ListNode*> nodes;
ListNode* pNode = head;
while (pNode != NULL){
nodes.push(pNode);
pNode = pNode -> next;
}
while (!nodes.empty()){
pNode = nodes.top();
res.push_back(pNode -> val);
nodes.pop();
}
return res;
}
};