Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes InterviewBytes/ListNode.java Secret
Created Jun 9, 2017

Embed
What would you like to do?
Reorder linked list
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
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
You can’t perform that action at this time.