Problem:
Reverse a singly linked list.
Solution:
//my solution
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head == NULL || head->next == NULL) return head;
ListNode* it = head;
ListNode* prev = NULL;
ListNode* next = it->next;
while(1)
{
it->next = prev;
prev = it;
it = next;
if(it == NULL) break;
next = it->next;
}
head = prev;
return head;
}
};
//recursion solution
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !(head -> next)) return head;
ListNode* node = reverseList(head -> next);
head -> next -> next = head;
head -> next = NULL;
return node;
}
};
网友评论