从尾到头打印链表
题目:
输入一个链表,按链表从尾到头的顺序返回一个ArrayList。
思路:
1.顺序加入列表,反转列表
2.反转链表再加入链表
3.递归
代码:
// 1.反转列表
/**
* 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!=NULL){
ans.push_back(head->val);
head = head->next;
}
reverse(ans.begin(),ans.end());
return ans;
}
};
// 2.反转链表
/**
* 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;
ListNode * last = NULL, * next;
while(head!=NULL){
next = head->next;
head->next = last;
last = head;
head = next;
}
head = last;
while(head!=NULL){
ans.push_back(head->val);
head = head->next;
}
return ans;
}
};
// 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> ans;
dfs(head, ans);
return ans;
}
void dfs(ListNode* head, vector<int> &ans) {
if(head == NULL) return;
dfs(head->next, ans);
ans.push_back(head->val);
}
};