力扣,https://leetcode.cn/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/description/
迭代也很简单,最佳方案还是递归
class Solution {
public int[] reverseBookList(ListNode head) {
List<Integer> resList = new ArrayList<>();
recur(head, resList);
int[] resArray = new int[resList.size()];
for (int i = 0; i < resList.size(); ++i) {
resArray[i] = resList.get(i);
}
return resArray;
}
public void recur(ListNode head, List<Integer> resList) {
if (head == null) {
return;
}
recur(head.next, resList);
resList.add(head.val);
}
}
Solution1:我的答案
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {//把链表节点的值从尾到头存到vector中
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> res;
if(head == NULL) return res;
ListNode* ptr=head;
while(ptr != NULL){
res.push_back(ptr->val);
ptr=ptr->next;
}
int i=0,temp=0,n=res.size(),j=n-1;
while(i<=j){
temp=res[i];
res[i]=res[n-1-i];
res[n-1-i]=temp;
i++;
j--;
}
return res;
}
};
Solution2:20180829重做
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
if (!head) return {};//特例
vector<int> res;
struct ListNode *cur = head;
while (cur) {
res.push_back(cur->val);
cur = cur->next;
}
reverse(res.begin(), res.end());
return res;
}
};