[算法]按照左右半区的方式重新整合单链表

题目:

给定一个单列表的头部节点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

转载于:https://www.cnblogs.com/xiaomoxian/p/5254964.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值