题目
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
思路
分三步:
1.找到链表的中间位置拆分链表。
2.后一个链表反转
3.前一个链表和后一个链表间隔插入
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if(head==null || head.next==null){
return;
}
//找中间结点
ListNode a=head;
ListNode b=head;
while(true){
if(b.next==null || b.next.next==null){
break;
}
a=a.next;
b=b.next.next;
}
//拆分
ListNode aa=a.next;
a.next=null;
//第二个链表反转
if(aa.next==null){
}else{
ListNode f=aa.next;
ListNode bf=aa;
while(true){
if(f==null){
break;
}
bf.next=f.next;
f.next=aa;
aa=f;f=bf.next;
}
}
//间隔插入
ListNode h=head;
while(true){
if(aa==null){
break;
}
ListNode aaa=aa.next;
aa.next=h.next;
h.next=aa;
aa=aaa;
h=h.next.next;
}
}
}