Skip to content

Instantly share code, notes, and snippets.

@mding5692
Created October 9, 2016 18:01
Show Gist options
  • Save mding5692/1f0bcb097e9abe02b847cc4103f4bdf2 to your computer and use it in GitHub Desktop.
Save mding5692/1f0bcb097e9abe02b847cc4103f4bdf2 to your computer and use it in GitHub Desktop.
Tech Interview prep practice - answers
/**
* 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> smallerList = new ArrayList<Integer>();
ArrayList<Integer> largerList = new ArrayList<Integer>();
ListNode curr = head;
while (head != null) {
if (head.val < x) {
smallerList.add(head.val);
} else {
largerList.add(head.val);
}
head = head.next;
}
ListNode newHead = curr;
for (int i : smallerList) {
curr.val = i;
curr = curr.next;
}
for (int i:largerList) {
curr.val = i;
curr= curr.next;
}
return newHead;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment