链表基本功
1. 找到中点;
2. 对链表后半部分反转;
3. 将前半部分和后半部分拼接
/**
* 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;
}
ListNode fn = head.next.next, sn = head;
while (fn != null && fn.next != null) {
sn = sn.next;
fn = fn.next.next;
}
if (fn != null) {
sn = sn.next;
}
ListNode rightHalf = reverse(sn.next);
sn.next = null;
while (rightHalf != null) {
ListNode temp1 = head.next;
head.next = rightHalf;
ListNode temp2 = rightHalf.next;
rightHalf.next = temp1;
head = temp1;
rightHalf = temp2;
}
}
private ListNode reverse(ListNode node) {
ListNode prev = null;
while (node != null) {
ListNode temp = node.next;
node.next= prev;
prev = node;
node = temp;
}
return prev;
}
}
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}
.