Skip to content

Instantly share code, notes, and snippets.

@IngeFrodo
Last active August 27, 2020 00:04
Show Gist options
  • Save IngeFrodo/4d6745cc378cbd607da88c2c59f11302 to your computer and use it in GitHub Desktop.
Save IngeFrodo/4d6745cc378cbd607da88c2c59f11302 to your computer and use it in GitHub Desktop.
class ReorderList {
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 curr = head;
ListNode revCurr = reverse(slow.next);
slow.next = null;
while (curr != null && revCurr != null) {
ListNode next = curr.next;
ListNode revNext = revCurr.next;
curr.next = revCurr;
curr = next;
revCurr.next = next;
revCurr = revNext;
}
}
private ListNode reverse(ListNode head) {
ListNode curr = head;
ListNode prev = null;
while (curr != null) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
}
return prev;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment