reverse a list:
//iterative
ListNode* reverse(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode dummy(0);
dummy.next = head;
head = &dummy;
ListNode* cur = head->next;
while(cur->next != NULL) {
ListNode* tmp = cur->next;
cur->next = tmp->next;
tmp->next = head->next;
head->next = tmp;
}
return head->next;
}
//recursive
ListNode* reverse(ListNode* head) {
if (head == NULL || head->next == NULL) return head;
ListNode* next=head->next;
ListNode* newhead= reverse(next);
next->next=head;
head->next=NULL;
return newhead;
}
No comments:
Post a Comment