[算法]按照左右半區的方式重新整合單鏈表


題目:

給定一個單列表的頭部節點head,鏈表長度為N,如果N為偶數,那么前N/2個節點算作左半區,后N/2個節點算作右半區。如果N為奇數,那么前N/2個節點算作左半區,后N/2+1個節點算作右半區。左半區依次記作L1->L2->…,右半區從左到右依次記為R1->R2->…,請將單鏈表調整成L1->R1->L2->R2->…的形式。

 

程序:

class Test{
public static void main(String[] args) {
Node head
=new Node(1);
head.next
=new Node(2);
head.next.next
=new Node(3);
head.next.next.next
=new Node(4);
head.next.next.next.next
=new Node(5);
head.next.next.next.next.next
=new Node(6);
head.next.next.next.next.next.next
=new Node(7);
print(head);
merge(head);
System.out.println();
print(head);
}
public static void merge(Node head){
if (head==null||head==null||head.next==null) {
return;
}
Node mid
=head;
Node cur
=head.next;
while(cur.next!=null&&cur.next.next!=null){
mid
=mid.next;
cur
=cur.next.next;
}
Node right
=mid.next;
mid.next
=null;
Node left
=head;
Node next
=null;
while(left.next!=null){
next
=right.next;
right.next
=left.next;
left.next
=right;
left
=right.next;
right
=next;
}
left.next
=right;


}
public static void print(Node head){
Node cur
=head;
while(cur!=null){
System.out.print(cur.value
+" ");
cur
=cur.next;
}
}
static class Node{
public int value;
public Node next;
public Node(int value){
this.value=value;
}
}
}

輸出結果:

QQ截圖20160308174741


注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
粤ICP备14056181号  © 2014-2020 ITdaan.com