从尾到头打印链表
题目描述
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
法一:非递归
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ans;
while(head){
ans.push_back(head -> val);
head = head -> next;
}
reverse(ans.begin(), ans.end());
return ans;
}
};
法二:非递归
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ans;
while(head){
ans.insert(ans.begin(), head -> val);
head = head -> next;
}
return ans;
}
};
法三:递归
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ans;
if(head != NULL){
ans = printListFromTailToHead(head -> next);
ans.push_back(head -> val);
}
return ans;
}
};

浙公网安备 33010602011771号