Advertisement
Guest User

Untitled

a guest
Jan 17th, 2018
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.24 KB | None | 0 0
  1. /**
  2.  * class ListNode {
  3.  *   public int value;
  4.  *   public ListNode next;
  5.  *   public ListNode(int value) {
  6.  *     this.value = value;
  7.  *     next = null;
  8.  *   }
  9.  * }
  10.  */
  11. public class Solution {
  12.   public ListNode reorder(ListNode head) {
  13.     // Write your solution here.
  14.     if (head == null || head.next == null) {
  15.       return head;
  16.     }
  17.     ListNode one = head;
  18.     ListNode mid = midNode(head);
  19.     ListNode two = mid.next;
  20.     mid.next = null;
  21.     two = reverse(two);
  22.    
  23.     ListNode curr = one;
  24.     while (one != null && two != null) {
  25.       one = one.next;
  26.       curr.next = two;
  27.       two = two.next;
  28.       curr.next.next = one;
  29.       curr = curr.next.next;
  30.     }
  31.     if (two == null) {
  32.       two = one;
  33.     }
  34.     return head;
  35.   }
  36.  
  37.   public ListNode midNode(ListNode head) {
  38.     ListNode slow = head;
  39.     ListNode fast = head;
  40.     while (fast.next != null && fast.next.next != null) {
  41.       slow = slow.next;
  42.       fast = fast.next.next;
  43.     }
  44.     return slow;
  45.   }
  46.  
  47.   public ListNode reverse(ListNode head) {
  48.     if (head == null || head.next == null) {
  49.       return head;
  50.     }
  51.     ListNode newHead = reverse(head.next);
  52.     head.next.next = head;
  53.     head.next = null;
  54.     return newHead;
  55.   }
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement