解题思路:
一.蛮力循环
二.讨论区的一种新思路:
例如对于链表1 2 3 4 5 6
先翻转为1 2 3 6 5 4
再转化为1 6 2 5 3 4
提交代码:蛮力循环
class Solution {
public void reorderList(ListNode head) {
if(head==null||head.next==null||head.next.next==null) return;
int len=1;
ListNode p1=head,p2=head;
while(p2.next!=null) {
p2=p2.next;
len++;
}
ListNode tmp=head.next;
p1.next=p2;
p2.next=tmp;
len-=2;
while(len>0) {
p1=p2.next;
p2=p1;
for(int i=1;i<len;i++)
p2=p2.next;
tmp=p1.next;
p1.next=p2;
p2.next=tmp;
len-=2;
}
p2.next=null;
}
}
运行结果:
提交代码:两次翻转
class Solution {
public void reorderList(ListNode head) {
if(head==null||head.next==null||head.next.next==null) return;
// 1 2 3 4 5 6 ===> 1 2 3 6 5 4
ListNode p1=head,p2=head,p3,pMid;
while(p2.next!=null&&p2.next.next!=null) {
p1=p1.next;
p2=p2.next.next;
}
p2=p1.next;pMid=p1;
while(p2.next!=null) {
p3=p2.next;
p2.next=p3.next;
p3.next=p1.next;
p1.next=p3;
}
// 1 2 3 6 5 4 ==> 1 6 2 5 3 4
p1=head;p2=pMid.next;
while(p1!=pMid) {
pMid.next=p2.next;
p2.next=p1.next;
p1.next=p2;
p1=p2.next;
p2=pMid.next;
}
}
}
运行结果: