题目链接:https://leetcode.com/problems/reorder-list/
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You may not modify the values in the list's nodes, only nodes itself may be changed.
Example 1:
Given 1->2->3->4, reorder it to 1->4->2->3.
Example 2:
Given 1->2->3->4->5, reorder it to 1->5->2->4->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 prev=null,fast=head,slow=head,l1=head;
while(fast!=null&&fast.next!=null){
prev=slow;
slow=slow.next;
fast=fast.next.next;
}
prev.next=null;
ListNode l2=reverse(slow);
merge(l1,l2);
}
public ListNode reverse(ListNode head){
if(head==null||head.next==null)
return head;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode prev=dummy.next;
ListNode cur=prev.next;
while(cur!=null){
prev.next=cur.next;
cur.next=dummy.next;
dummy.next=cur;
cur=prev.next;
}
return dummy.next;
}
public void merge(ListNode l1,ListNode l2){
while(l1!=null){
ListNode n1=l1.next;
ListNode n2=l2.next;
l1.next=l2;
if(n1==null){
break;//l1的长度是小于或等于l2的。
}
l2.next=n1;
l1=n1;
l2=n2;
}
}
}
思路:
(1)找到链表的中间节点。
对于例1例2,都是节点3。
(2)将后面的链表进行就地反转。
例1,反转为4->3;
例2,反转为5->4->3;
(3)合并两个链表。
AC 1ms beats 100% Java: