关键点:
- 1、将链表拆成左右两部分
- 2、合并左右两部分
//1、将链表从中间断开,分成左右两部分
public static Node reCombination(Node head) {
if(head == null || head.next == null || head.next.next == null) {
return head;
}
//找中点从中间断开
Node p1 = head.next.next;
Node p2 = head.next;
while(p1.next != null && p1.next.next != null) {
p1 = p1.next.next;
p2 = p2.next;
}//p2到达中点位置
Node right = p2.next;//右半部分链表头
p2.next = null;//断开
printList(head);
printList(right);
return mergeList(head,right);
}
//2、合并左右两部分
public static Node mergeList(Node left,Node right) {
if(left == null || right == null) return null;
Node head = left;
Node nextL = null;
Node nextR = null;
while(left.next != null) {
nextL = left.next;
left.next = right;
nextR = right.next;
left = nextL;
right.next = left;
right = nextR;
}
if(left != null) {
left.next = right;
}
return head;
}