给定一个链表,比如L1--->L2---->L3---->................----->Ln,把链表调整为L1---->Ln----->L2----->Ln-1------>L3------>Ln-3...........
要求:
1、间复杂度O(1);
思路:将后一半元素逆转之后,就可以按照后一半逆转之后的顺序插入到前一半链表中。
代码如下:
import java.util.*;
public class Main{
public static void main(String[]args){
Node1 n1=new Node1(1);
Node1 n2=new Node1(2);
Node1 n3=new Node1(3);
Node1 n4=new Node1(4);
Node1 n5=new Node1(5);
n1.next=n2;
n2.next=n3;
n3.next=n4;
n4.next=n5;
Node1 s=n1;
System.out.print("原始链表为:");
while(s!=null){
if(s.next!=null)
System.out.print(s.val+"->");
else
System.out.print(s.val);
s=s.next;
}
System.out.println();
n1=Change(n1);
s=n1;
System.out.print("转换后的链表为:");
while(s!=null){
if(s.next!=null)
System.out.print(s.val+"->");
else
System.out.print(s.val);
s=s.next;
}
}
public static Node1 Change(Node1 head){
int count=0;
Node1 t=head;
while(t!=null){
count++;
t=t.next;
}
t=head;
for(int i=0;i<count/2;i++){
t=t.next;
}
//首先翻转后一半的结点
t=Reverse(t);
//将后一半插入到前一半的链表中
Node1 r=head;
for(int i=0;i<count/2;i++){
Node1 temp=t.next;
Node1 temp2=r.next;
t.next=r.next;
r.next=t;
t=temp;
r=temp2;
}
return head;
}
public static Node1 Reverse(Node1 t){
if(t==null){
return null;
}
Node1 p=t;
Node1 q=t.next;
t.next=null;
while(q!=null){
Node1 r=q.next;
q.next=p;
p=q;
q=r;
}
return p;
}
}
class Node1{
int val;
Node1 next;
public Node1(int v){
this.val=v;
this.next=null;
}
}