[算法]按照左右半区的方式重新整合单链表
题目:
给定一个单列表的头部节点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; } } }