前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
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}
.
public class Solution {
public void reorderList(ListNode head) {
if(head != null && head.next != null && head.next.next != null){
ListNode p1 = head,p2 = head;
while(p2 !=null && p2.next != null){
p1 = p1.next;
p2 = p2.next.next;
}
ListNode head2 = p1.next,p3 = null,head1 = head;
p1.next = null;
p1 = null;p2 = head2;p3 = head2.next;
while( p2 != null && p2.next != null){
p2.next = p1;
p1 = p2;
p2 = p3;
p3 = p3.next;
}
p2.next = p1; head2 = p2;
p1 = head1.next; p2 = head2;
ListNode searchNode = head;
boolean flag = true;
while( p2 != null){
if(flag){
searchNode.next = p2;
p2 = p2.next;
}else{
searchNode.next = p1;
p1 = p1.next;
}
searchNode = searchNode.next;
flag = !flag;
}
searchNode.next = p1;
}
}
}