06. 从尾到头打印链表
class Solution {
public:
//两个指针一起走 一次翻转一个方向 最后head.next =null
ListNode* reverse1(ListNode *head){
if(!head)return NULL;
auto a=head,b=head->next;
while(b){
auto c=b->next;
b->next=a;//只反转一个方向
//指针往前走
a=b,b=c;
}
head->next=NULL;
return a;
}
vector<int> reversePrint(ListNode* head) {
head=reverse1(head);
vector<int>a;
while(head){
a.push_back(head->val);
head=head->next;
}
return a;
}
};
24. 反转链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head)return head;
if(!head->next)return head;
ListNode* tail =reverseList(head->next);
head->next->next=head;
head->next=NULL;
return tail;
}
};