链表重排
#define Node ListNode
#define null NULL
class Solution {
public:
void reorderList(ListNode *head) {
if(head == null||head->next==null) return ;
Node*first=head,*last=head, *pre=NULL;
while(first && first->next) first=first->next->next, pre = last,last=last->next;
Node* head2 = last;
pre->next = NULL;
head2 = reverse(head2);
merge(head,head2);
// return dummy.next;
}
Node* reverse(ListNode* h) {
if(h==null || h->next==null) return h;
Node *pre=null,*cur=h,*last=null;
while(cur) {
last = cur->next;
cur->next = pre;
pre = cur;
cur = last;
}
return pre;
}
Node* merge(Node* l,Node* r) {
Node dummy(0);
Node* x = &dummy;
int count=0;
while(l &&r) {
if(count%2==0) {
//第一个
x->next = l;
l = l->next;//l1
x = x->next;//l0
x->next = NULL;
}else{
//第二个
x->next = r;
r = r->next;
x = x->next;
x->next = NULL;
}
++count;
}
if(l) x->next = l;
if(r) x->next = r;
return dummy.next;
}
};