Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 9, 2017 15:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save InterviewBytes/50a1a04659bfbe0efcd6db86a34a6a29 to your computer and use it in GitHub Desktop.
Save InterviewBytes/50a1a04659bfbe0efcd6db86a34a6a29 to your computer and use it in GitHub Desktop.
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