143. rearrangement list
Given a single chain L: L0 → L1 → ... → Ln-1 → Ln,
after rearranging changed: L0 → Ln → L1 → Ln -1 → L2 → Ln-2 → ...
You can not just simply change the internal node values, but need to be the actual node exchange.
Example 1:
Given list 1-> 2-> 3-> 4, is rearranged 1-> 4-> 2-> 3.
Example 2:
Given list 1-> 2-> 3-> 4-> 5, rearranged 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) {
return;
}
ListNode fast = head, slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
ListNode cur = slow.next, pre = null, next = null;
slow.next = null;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
ListNode p1 = head, p2 = pre;
while (p1 != null && p2 != null) {
next = p2.next;
p2.next = p1.next;
p1.next = p2;
p1 = p2.next;
p2 = next;
}
}
}