Skip to content

Instantly share code, notes, and snippets.

@InterviewBytes
Created June 9, 2017 02:02
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/7918b715aa0d3efa12932101df7db50b to your computer and use it in GitHub Desktop.
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.
package com.interviewbytes.linkedlists;
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
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