题目链接: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 must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.
*
*/
public class ReorderList {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
// 13 / 13 test cases passed.
// Status: Accepted
// Runtime: 337 ms
// Submitted: 23 minutes ago
public void reorderList(ListNode head) {
ListNode midNode = head;
ListNode lastNode = head;
//找到链表的中点
while(lastNode.next != null && lastNode.next.next != null) {
midNode = midNode.next;
lastNode = lastNode.next.next;
}
lastNode = midNode.next;
//断开链表
midNode.next = null;
//反转后半链表
midNode = reverseList(lastNode);
//合并链表
ListNode cur = head;
while( midNode != null) {
ListNode node = cur.next;
cur.next = midNode;
midNode = midNode.next;
cur = cur.next;
cur.next = node;
cur = cur.next;
}
}
public ListNode reverseList(ListNode head) {
ListNode preHead = new ListNode(Integer.MAX_VALUE);
while(head != null) {
ListNode node = preHead.next;
preHead.next = head;
head = head.next;
preHead.next.next = node;
}
return preHead.next;
}
public static void main(String[] args) {
System.out.println(Math.ceil(1.0 / 2.0));
}
}