题目链接:https://leetcode-cn.com/problems/cong-wei-dao-tou-da-yin-lian-biao-lcof/
题目如下:
解一:反转链表
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head){
ListNode* pre=NULL,*cur=head;
while(cur!=NULL){
ListNode* temp=cur->next;
cur->next=pre;
pre=cur;cur=temp;
}
return pre;
}
vector<int> reversePrint(ListNode* head) {
ListNode* list=reverse(head);
vector<int> result;
while(list!=NULL){
result.push_back(list->val);
list=list->next;
}
return result;
}
};
解二:递归
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<int> reversePrint(ListNode* head) {
//递归
vector<int> ans;
dfs(ans,head);
return ans;
}
void dfs(vector<int>& ans,ListNode* head){//ans为地址传递
if(head==NULL) return ;
dfs(ans,head->next);
ans.push_back(head->val);
}
};