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}
.
题意:将原链表分成两等份,然后翻转后一段,最后按要求归并
void reorderList(ListNode *head) {
ListNode *p = head;
ListNode *q = head;
if(!p || !p->next || !p->next->next) return ;
while(p && p->next){//分成两分
p = p->next->next;
q = q->next;
}
p = q->next;
q->next = NULL;
ListNode *pre = NULL;
//后一段翻转
while(p->next){
q = p->next;
p->next = pre;
pre = p;//r记录前一个已处理的节点
p = q;
}
p->next = pre;
ListNode *p1;
ListNode *q1;
q = head;
//合并
while(p && q){
q1 = q->next;
p1 = p->next;
q->next = p;
p->next = q1;
p = p1;
q = q1;
}
}