-
-
Save InterviewBytes/7918b715aa0d3efa12932101df7db50b to your computer and use it in GitHub Desktop.
Partition linkedlist such that all nodes less than x come before nodes greater than or equal to 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 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 Partition { | |
public ListNode partition(ListNode head, int x) { | |
ListNode lesserSentinel = new ListNode(0); | |
ListNode greaterSentinel = new ListNode(0); | |
ListNode currentLesser = lesserSentinel; | |
ListNode currentGreater = greaterSentinel; | |
while (head != null) { | |
if (head.val < x) { | |
currentLesser.next = head; | |
currentLesser = currentLesser.next; | |
} else { | |
currentGreater.next = head; | |
currentGreater = currentGreater.next; | |
} | |
head = head.next; | |
} | |
currentLesser.next = greaterSentinel.next; | |
currentGreater.next = null; | |
return lesserSentinel.next; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment