Given a singly linked list L: L0 → L1 → … → Ln-1 → Ln
reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → …
Example
Given 1->2->3->4->null
, reorder it to 1->4->2->3->null
.
Challenge
Can you do this in-place without altering the nodes‘ values?
/** * 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) { // write your code here if(head == null || head.next == null || head.next.next == null) return; ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; } ListNode head2 = slow.next; slow.next = null; head2 = reverse(head2); ListNode p1 = head; ListNode p2 = head2; ListNode p1_next = head.next; ListNode p2_next = head2.next; while(p1_next != null && p2_next != null){ p1.next = p2; p2.next = p1_next; p1 = p1_next; p2 = p2_next; p1_next = p1_next.next; p2_next = p2_next.next; } p1.next = p2; p2.next = p1_next; return; } public ListNode reverse(ListNode head){ if(head == null || head.next == null) return head; ListNode prev = head; ListNode curr = head.next; ListNode next = head.next.next; head.next = null; while(next != null){ curr.next = prev; prev = curr; curr = next; next = next.next; } curr.next = prev; return curr; } }
时间: 2024-10-13 16:47:22