86 Partition List
86. Partition List
1. Question
2. Implementation
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null) {
return head;
}
ListNode less = new ListNode(0);
ListNode equalOrMore = new ListNode(0);
ListNode p1 = less;
ListNode p2 = equalOrMore;
ListNode curNode = head;
while (curNode != null) {
if (curNode.val < x) {
p1.next = curNode;
p1 = p1.next;
}
else {
p2.next = curNode;
p2 = p2.next;
}
curNode = curNode.next;
}
p2.next = null;
p1.next = equalOrMore.next;
return less.next;
}
}3. Time & Space Complexity
Last updated