/**
* 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 == NULL || head->next == NULL) return head;
ListNode* cur = head;
ListNode* prev = NULL;
while(cur != NULL){
ListNode* next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};
/**
* 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 == NULL || head->next == NULL) return head;
return getreverse(NULL,head);
}
ListNode* getreverse(ListNode* prev,ListNode* cur){ //每一次递归就相当于将cur和prev向前移动
if(cur == NULL){
return prev;
}
ListNode* next = cur->next;
cur->next = prev;
return getreverse(cur,next);
}
};