143. Reorder List
problem description
Given 1->2->3->4, reorder it to 1->4->2->3.Given 1->2->3->4->5, reorder it to 1->5->2->4->3.algorithm thought
code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void reorderList(ListNode* head) {
head=reorder(head);
}
ListNode* reorder(ListNode* head){
if(head==NULL||head->next==NULL||head->next->next==NULL)
return head;
ListNode* tmp=head;
while(head->next->next){
head=head->next;
}
head->next->next=tmp->next;
tmp->next=head->next;
head->next=NULL;
tmp->next->next=reorder(tmp->next->next);
return tmp;
}
};algorithm analysis
Last updated