Last active
August 27, 2020 00:04
-
-
Save IngeFrodo/4d6745cc378cbd607da88c2c59f11302 to your computer and use it in GitHub Desktop.
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
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