My solution:
1. The solution I wrote, happy, and finally remember the reverse linked list
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head) return nullptr;
ListNode* i=head;
ListNode* j=head->next;
i->next=NULL;
while(j){
ListNode* now=j->next;
j->next=i;
i=j;
j=now;
}
return i;
}
};
2. Recursion
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL || head->next==NULL) return head;
ListNode* p=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return p;
}
};