题目:
Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given{1,2,3,4}, reorder it to{1,4,2,3}.
分析:
这道题可以分三个步骤来解决。一、找到原链表的中间位置,以这个中间位置为基准将链表分为两段;二、将处在后半段的链表进行反转;三、将两个链表进行融合。
具体的代码如下:
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public static void reorderList(ListNode head) {
if (head == null || head.next == null)
return ;
ListNode mid = findMiddle(head);
ListNode aft = mid.next;
mid.next = null;
ListNode pre = head;
aft = reverse(aft);
merge(pre, aft);
}
public static ListNode reverse(ListNode aft){
ListNode l1 = aft;
ListNode l2 = aft.next;
while(l2 != null){
ListNode tmp = l2.next;
l2.next = l1;
l1 = l2;
l2 = tmp;
}
aft.next = null;
return l1;
}
public static void merge(ListNode pre, ListNode aft){
while (aft != null){
ListNode aftN = aft.next;
ListNode preN = pre.next;
pre.next = aft;
aft.next = preN;
aft = aftN;
pre = preN;
}
}
public static ListNode findMiddle(ListNode head){
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}