[leetcode] Reverse Linked List
[leetcode] Reverse Linked List
Iterative
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *prev = NULL;
ListNode *cur = head;
while(cur) {
ListNode *temp = cur->next;
cur->next = prev;
prev = cur;
cur = temp;
}
return prev;
}
};
Recursive
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};