Skip to content

Instantly share code, notes, and snippets.

@mding5692
Created February 14, 2016 21:08
Show Gist options
  • Save mding5692/70e3fc2b64af81343689 to your computer and use it in GitHub Desktop.
Save mding5692/70e3fc2b64af81343689 to your computer and use it in GitHub Desktop.
partitionList - for Western Tech Interview Prep Q1
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null) {
return head;
}
ArrayList<Integer> greaterThanX = new ArrayList<Integer>();
ArrayList<Integer> lessThanX = new ArrayList<Integer>();
ListNode curr = head;
while (true) {
int val = curr.val;
if (val >= x) {
greaterThanX.add(val);
} else {
lessThanX.add(val);
}
if (curr.next != null) {
curr = curr.next;
} else {
break;
}
}
int lessThanXAmount = lessThanX.size();
int greaterThanXAmount = greaterThanX.size();
ListNode origHead = head;
int i = 0;
while (i < lessThanXAmount) {
head.val = lessThanX.get(i);
head = head.next;
i++;
}
int j = 0;
while (j < greaterThanXAmount) {
head.val = greaterThanX.get(j);
head = head.next;
j++;
}
return origHead;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment