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 Solution {
- public void reorderList(ListNode head) {
- if(head==null||head.next == null) return;
- ListNode slow = head;
- ListNode fast = head;
- while(slow!=null&&fast!=null&&fast.next!=null){
- slow = slow.next;
- fast = fast.next.next;
- }
- ListNode mid = slow.next;
- ListNode last = mid;
- ListNode pre = null;
- while(last!=null){
- ListNode t = last.next;
- last.next = pre;
- pre = last;
- last = t;
- }
- slow.next = null;
- while(head!=null&&pre!=null){
- ListNode t = head.next;
- head.next = pre;
- pre = pre.next;
- head.next.next = t;
- head = t;
- }
- }
- }
原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46564187