https://leetcode-cn.com/problems/reorder-list/
本题重点是要发现
重排链表的结果等于进行如下操作后的结果
1.对后半部分链表进行反转
2.合并前后部分,“前1后1前2后2…”
如何找到链表中点?可以使用快慢指针的方式。不难发现,本题是以往链表题的结合。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public void reorderList(ListNode head) {
if(head==null) return;
ListNode left=head;
ListNode mid=getMid(head);
ListNode right=mid.next;
mid.next=null;
right=reverse(right);
merge(left,right);
}
//如果偶数个,停在左边的中间节点
public ListNode getMid(ListNode head){
ListNode fast=head;
ListNode slow=head;
while(fast.next!=null&&fast.next.next!=null){
fast=fast.next.next;
slow=slow.next;
}
return slow;
}
public ListNode reverse(ListNode head){
ListNode cur=head;
ListNode pre=null;
while(cur!=null){
ListNode tmp=cur.next;
cur.next=pre;
pre=cur;
cur=tmp;
}
return pre;
}
public void merge(ListNode L1,ListNode L2){
ListNode a;
ListNode b;
while(L1!=null&&L2!=null){
a=L1.next;
b=L2.next;
L1.next=L2;
L1=a;
L2.next=L1;
L2=b;
}
}
}