面试题6:从后往前打印链表 题目链接
/**
* 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) {
/* 思路:遍历过程中不断将值压栈,最后弹栈输出
时间复杂度 O(n)
空间复杂度 O(n)
*/
stack<int> sk;
vector<int> ans;
while(head != NULL){
sk.push(head->val);
head = head->next;
}
while(!sk.empty()){
ans.push_back(sk.top());
sk.pop();
}
return ans;
}
};