[算法]按照左右半区的方式重新整合单链表
2016-03-08 17:50
435 查看
题目:
给定一个单列表的头部节点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; } } }
输出结果:
相关文章推荐
- 带左右按钮、 渐隐渐现 轮播图
- 数独 (dfs)
- 关于代理arp的原理以及通信过程解析
- 第一天:NodeJs Windows环境搭建、学习资料地址、注意事项总结
- linux双网卡配置路由
- Hadoop MapReduce作业提交与初始化过程分析
- 再探epoll实现机制
- JVM内存管理和JVM垃圾回收机制
- Java 9.10习题
- 蓝桥杯 地宫寻宝
- js ES6 对字符的操作注意事项
- c++下可调对象作为参数的实现
- 基于第三方统计工具做的网站访问次数统计。
- C++初始化列表
- 解除笔记本电脑的无法连接无线网
- python入门(三)
- Handler当做内部类,导致内存泄露的问题
- 周更学习进度
- 渐隐渐现切换效果
- Android网络通信之Socket