给你一个链表的头节点 head
和一个特定值 x
,请你对链表进行分隔,使得所有 小于 x
的节点都出现在 大于或等于 x
的节点之前。
你应当 保留 两个分区中每个节点的初始相对位置。
示例 1:
输入:head = [1,4,3,2,5,2], x = 3 输出:[1,2,2,4,3,5]
示例 2:
输入:head = [2,1], x = 2 输出:[1,2]
提示:
- 链表中节点的数目在范围
[0, 200]
内 -100 <= Node.val <= 100
-200 <= x <= 200
package Solution86;
import java.util.Comparator;
import java.util.PriorityQueue;
class Solution {
public ListNode partition(ListNode head, int x) {
if (head == null || head.next == null)
return head;
ListNode dummy1 = new ListNode(-1);
ListNode s = dummy1;
ListNode dummy2 = new ListNode(-1);
ListNode b = dummy2;
ListNode curr = head;
while (curr != null) {
if (curr.val < x) {
s.next = curr;
s = s.next;
} else {
b.next = curr;
b = b.next;
}
curr = curr.next;
}
b.next = null;
s.next = dummy2.next;
return dummy1.next;
}
public ListNode rotateRight(ListNode head, int k) {
if (head == null) {
return head;
}
if (k == 0) {
return head;
}
int count = 0;
ListNode start = head;
// traverse till the end of the list and keep incrementing
// count
while (head.next != null) {
head = head.next;
count++;
}
count++;
// if k > count, do k%count, its an optimization. 2%5 == 12%5
k = k % count;
// find the new k
k = Math.abs(count - k);
if (k == 0)
return start;
// connect last element to start
head.next = start;
// traverse for new k value
while (k-- > 0) {
head = head.next;
}
// note: head is not the last element, so set the start.
start = head.next;
head.next = null;
return start;
}
public ListNode mergeKLists(ListNode[] lists) {
if (lists == null || lists.length == 0)
return null;
PriorityQueue<ListNode> queue = new PriorityQueue<ListNode>(
(Comparator<? super ListNode>) new Comparator<ListNode>() {
public int compare(ListNode l1, ListNode l2) {
return l1.val - l2.val;
}
});
ListNode head = new ListNode(0);
ListNode p = head;
for (ListNode list : lists) {
if (list != null)
queue.offer(list);
}
while (!queue.isEmpty()) {
ListNode n = queue.poll();
p.next = n;
p = p.next;
if (n.next != null)
queue.offer(n.next);
}
return head.next;
}
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null)
return l1;
if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
public ListNode removeElements(ListNode head, int val) {
ListNode header = new ListNode(-1);
header.next = head;
ListNode cur = header;
while (cur.next != null) {
if (cur.next.val == val) {
cur.next = cur.next.next;
} else {
cur = cur.next;
}
}
return header.next;
}
void printList(ListNode node) {
while (node != null) {
System.out.print(node.val + " ");
node = node.next;
}
}
public static void main(String[] args) {
Solution sol = new Solution();
ListNode head = new ListNode(1);
head.next = new ListNode(4);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(2);
head.next.next.next.next = new ListNode(5);
head.next.next.next.next.next = new ListNode(2);
int x = 3;
sol.printList(sol.partition(head, x));
}
}