/**
* 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 || !head->next) {
return head;
}
ListNode *cur = head->next, *next = NULL;
head->next = NULL;
while (cur) {
next = cur->next;
cur->next = head;
head = cur;
cur = next;
}
return head;
}
};
Recursive
class Solution {
public:
ListNode *recursiveReverse(ListNode *head, ListNode *p) {
if (!p) {
return head;
}
ListNode *next = p->next;
p->next = head;
return recursiveReverse(p, next);
}
ListNode* reverseList(ListNode* head) {
return recursiveReverse(NULL, head);
}
};