Description:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
问题描述:
给一条单链表,有n+1个结点,将第n个结点插入到第0个结点与第1个结点之间,将第n-1个结点插入到第1个结点与第2个结点之间,依次类推。
Ex:
Given {1,2,3,4}, reorder it to {1,4,2,3}.
解法一:
思路:
看到这种处理最后一个元素(第n个结点)开始的操作,本能想到用快慢指针,但是这种插入操作,最多只能插入链表总长度一半的元素。所以,主要的步骤分三步处理,先将整条链表切分成前半部分和后半部分,第二步,将后半部分链表逆序(非常重要,又出现了,一定要背下来)。第三步,完成逆序后的后半部分链表和前半部分的拼接操作。
Code:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public void reorderList(ListNode head) {
if(head == null || head.next == null)
return;
//Step1: Cut the list to two halves
//prev will be the tail of the 1st half
//slow will be the head of the 2nd half
ListNode prev = null;
ListNode slow = head, fast = head,l1 =head;
while(fast != null && fast.next != null){
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
//Step2: reverse the 2nd half
ListNode l2 = reverse(slow);
//Step3: merge the two halves
merge(l1,l2);
}
private ListNode reverse(ListNode head){
ListNode prev = null, curr = head, next =null;
while(curr != null){
next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
private void merge(ListNode l1, ListNode l2){
while(l1 != null){
ListNode n1 = l1.next, n2 = l2.next;
l1.next = l2;
if(n1 == null)
break;
l2.next = n1;
l1 = n1;
l2 = n2;
}
}
}