样例
链表:1 2 3 4 5 6 7 8 9 10 前半部和后半部重新组合,结果:1 6 2 7 3 8 4 9 5 10
java代码
* @Description:按照左右半区的方式重新组合成新链表
* @Author: lizhouwei
* @CreateDate: 2018/4/7 17:45
* @Modify by:
* @ModifyDate:
*/
public class Chapter2_20 {
public Node relocation(Node head) {
if (head == null) {
return null;
}
Node node1 = head;
Node node2 = head; //node2 以head开始 ,或者以 head.next开始,最终node1都是链表的中间节点
//node1走一步,node2走两步,当node2.next.next走到结尾的时候node1所在的位置为链表的中间节点
//例如:链表为 1-2-3-4-5-6-7-8-9-10 node1=5,node2=9时,node1为中间节点
while (node2.next != null && node2.next.next != null) {
node1 = node1.next;
node2 = node2.next.next;
}
node2 = node1.next;
node1.next = null;
node1 = head;
Node next = null;
while (node1 != null) {
next = node2.next;//node2的后继节点
node2.next = node1.next;//node2的后继节点指向node1的后继节点
node1.next = node2;//node1的后继节点指向node2,node2插入到了原始node1和node1.next中间了
node1 = node2.next;//取出原始node1的后继节点,此时是node2的后继节点
node2 = next;
}
return head;
}
//测试
public static void main(String[] args) {
Chapter2_20 chapter = new Chapter2_20();
Link link = new Link();
//构造链表
for (int i = 10; i > 0; i--) {
link.add(i);
}
Link.printLink(link.head);
Node head = chapter.relocation(link.head);
Link.printLink(head);
}
}