先用快慢指针找到中点,然后将后半部分进行翻转,最后在对这两个链表进行合并。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverse(ListNode* head){
if(head==NULL||head->next==NULL) return head;
ListNode* newhead=reverse(head->next);
head->next->next=head;
head->next=NULL;
return newhead;
}
void reorderList(ListNode *head) {
if(head==NULL||head->next==NULL) return ;
ListNode *fast=head,*slow=head;
while(fast&&fast->next){
fast=fast->next->next;
slow=slow->next;
}
ListNode *head2=reverse(slow->next);
slow->next=NULL;
ListNode *newhead=new ListNode(0),*p=newhead;
while(head&&head2){
p->next=head;
head=head->next;
p=p->next;
p->next=head2;
head2=head2->next;
p=p->next;
}
if(head) p->next=head;
if(head2) p->next=head2;
head=newhead->next;
}
};