从尾到头打印链表
1.题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
2.思路
利用栈实现,没遍历一个节点就插入栈。
3.代码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if(head == NULL){
return res;
}
stack<int> s;
while(head != NULL){
s.push(head->val);
head = head->next;
}
while(!s.empty()){
int val = s.top();
s.pop();
res.push_back(val);
}
return res;
}
};
4.复杂度分析
时间复杂度:O(n)
空间复杂度:O(n)