-
-
Save InterviewBytes/50a1a04659bfbe0efcd6db86a34a6a29 to your computer and use it in GitHub Desktop.
Reorder linked list
This file contains 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
package com.interviewbytes.linkedlists; | |
public class ListNode { | |
int val; | |
ListNode next; | |
ListNode(int x) { | |
val = x; | |
} | |
} |
This file contains 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
package com.interviewbytes.linkedlists; | |
public class ReoderList { | |
public void reorderList(ListNode head) { | |
if (head == null || head.next == null) return; | |
ListNode slow = head; | |
ListNode fast = head; | |
while (fast != null && fast.next != null) { | |
slow = slow.next; | |
fast = fast.next.next; | |
} | |
ListNode reversed = null; | |
while (slow != null) { | |
ListNode next = slow.next; | |
slow.next = reversed; | |
reversed = slow; | |
slow = next; | |
} | |
ListNode current = new ListNode(0); | |
boolean odd = true; | |
while (head != null && reversed != null) { | |
if (odd) { | |
current.next = head; | |
head = head.next; | |
} else { | |
current.next = reversed; | |
reversed = reversed.next; | |
} | |
current = current.next; | |
odd = !odd; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment