给定一个单向链表L(N0,N1,N2,N3……),在不改变node值得情况下,来编程实现对链表重新排列 ,使得排序后的链表为(N0,Nn,n1,Nn-1,n2,Nn-2……)。

来源:互联网 发布:软件编程网站 编辑:程序博客网 时间:2024/05/17 22:25
package Test;


//给定一个单向链表L(N0,N1,N2,N3……),在不改变node值得情况下,来编程实现对链表重新排列
//使得排序后的链表为(N0,Nn,n1,Nn-1,n2,Nn-2……)。
//思路:用快慢指针截断前后两段链表,后半段链表反转,交叉拼接前半段和后半段链表
public class linkTest {

public static void main(String[] args) {
Node head=new Node(0);
Node tmp=new Node();
tmp=null;
Node cur=new Node();
cur=null;
for(int i=1;i<10;i++)
{
tmp=new Node(i);
if(i==1)
head.setNext(tmp);
else 
cur.setNext(tmp);
cur = tmp; 
}

Node h = head;   
       while (null != h) {   
           System.out.print(h.getValue() + " ");   
           h = h.getNext();   
       }   
}
    //重排链表
public static Node linkSort(Node head) {
if (head == null)
return null; // 快慢指针寻找中间节点,一个指针一步,一个指针两步,当两步的指针走到了最后,1步的指针刚好走到中间
Node first = new Node();
first=head;
Node second = new Node();
second=head;
//查找中间节点
while (second.next != null) {
second = second.next;
first = first.next;
if (second.next != null) {//first移动一步,second移动两步, null.next报错,故要分开,
second = second.next;
}
} // 截取后半段链表
second = first.next;//这是first指向中间结点
first.next = null; // 反转后半段链表 
Node cur = second; Node rhead = null;
while(cur!=null){
Node front = cur; 
cur =cur.next; 
front.next = rhead; 
rhead = front; 
}
//拼接两段链表 
Node nhead = head;
while(nhead!=null&&rhead!=null){
Node temp =nhead.next; 
Node rtemp = rhead.next; 
nhead.next =rhead;
rhead.next = temp; 
nhead = temp; 
rhead =rtemp; 
}
if(rhead!=null) //前后半段一样长的处理
nhead.next= rhead; 
return head; 
}


}



0 0
原创粉丝点击