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.
Example
For example,
Given 1->2->3->4->null, reorder it to 1->4->2->3->null.
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The head of linked list. * @return: void */ public void reorderList(ListNode head) { if (head == null || head.next == null){ return; } ListNode mid = findMid(head); ListNode node = mid.next; mid.next = null; node = reverse(node); head = merge(head, node); } private ListNode findMid(ListNode head){ if (head == null || head.next == null){ return head; } ListNode fast = head; ListNode slow = head; while (fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } return slow; } private ListNode reverse(ListNode head){ if (head == null){ return head; } ListNode prev = null; while (head != null){//错误的地方 ListNode temp = head.next; head.next = prev; prev = head; head = temp; } return prev; } private ListNode merge(ListNode l1, ListNode l2){ if (l1 == null){ return l2; } if (l2 == null){ return l1; } ListNode dummy = new ListNode(0); ListNode head = dummy; while (l1 != null && l2 != null){ head.next = l1; head = l1; l1 = l1.next; head.next = l2; head = l2; l2 = l2.next; } if (l1 != null){ head.next = l1; } if (l2 != null){ head.next = l2; } return dummy.next; } }
原文:http://www.cnblogs.com/tritritri/p/4971175.html