Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}
, reorder it to {1,4,2,3}
.
确定链表长度后将后半段反序再与前半段合并就可以了,记住前后两段一定要断开不然会产生环
/** * 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) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head==NULL)return; if(head->next==NULL)return; int count=0; ListNode* ptr=head; while(ptr!=NULL){ count++; ptr=ptr->next; } int len; if(count%2==0)len=count/2; else len=count/2+1; ptr=head; for(int i=0;i<len-1;i++)ptr=ptr->next; ListNode* tmp; ListNode* ptr2=ptr->next; ptr->next=NULL; ptr=ptr2; ptr2=ptr->next; while(ptr2!=NULL){ tmp=ptr2->next; ptr2->next=ptr; ptr=ptr2; ptr2=tmp; } ptr2=head; len=count/2; for(int i=0;i<len;i++){ tmp=ptr2->next; ptr2->next=ptr; ptr2=tmp; tmp=ptr->next; ptr->next=ptr2; ptr=tmp; } } };