Created
September 2, 2015 04:55
-
-
Save cxtadment/c393bd28e303bf36b261 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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) { | |
| return; | |
| } | |
| ListNode midNode = getMid(head); | |
| ListNode rev = reverse(midNode.next); | |
| midNode.next = null; | |
| merge(head, rev); | |
| } | |
| public ListNode getMid(ListNode head) { | |
| ListNode slow = head, fast = head.next; | |
| while (fast != null && fast.next != null) { | |
| fast = fast.next.next; | |
| slow = slow.next; | |
| } | |
| return slow; | |
| } | |
| public ListNode reverse(ListNode head) { | |
| ListNode newNode = null; | |
| while (head != null) { | |
| ListNode temp = head.next; | |
| head.next = newNode; | |
| newNode = head; | |
| head = temp; | |
| } | |
| return newNode; | |
| } | |
| public void merge(ListNode head, ListNode rev) { | |
| int index = 0; | |
| ListNode dummy = new ListNode(0); | |
| while (head != null && rev != null) { | |
| if (index % 2 == 0) { | |
| dummy.next = head; | |
| head = head.next; | |
| } else { | |
| dummy.next = rev; | |
| rev = rev.next; | |
| } | |
| dummy = dummy.next; | |
| index++; | |
| } | |
| if (head != null) { | |
| dummy.next = head; | |
| } else { | |
| dummy.next = rev; | |
| } | |
| } | |
| } | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment