题目描述
从尾到头打印链表:
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
分析
栈、翻转、递归
1.可将在从头至尾逐个遍历链表的时,将各节点值存入栈中,完毕后,再依次出栈存入vector中即可。
2.直接在遍历过程中将值存入vector中,之后再reverse vector即可。
3.利用递归,将当前节点值push_back到其next的输出vector中。
…
源码
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
//1.翻转vector的方法。
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> array;
ListNode* ptemp = head;
while(ptemp!=NULL){
array.push_back(ptemp->val);
ptemp = ptemp->next;
}
reverse(array.begin(),array.end());
return array;
}
};