Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
[分析] 想到创建两个辅助链表就好办了,small链表存储小于x的节点,large链表存储大于x的节点,最后merge两个链表。
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.
[分析] 想到创建两个辅助链表就好办了,small链表存储小于x的节点,large链表存储大于x的节点,最后merge两个链表。
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode small = new ListNode(-1);
ListNode large = new ListNode(1);
ListNode pSmall = small;
ListNode pLarge = large;
ListNode curr = head;
while (curr != null) {
if (curr.val < x) {
pSmall.next = curr;
pSmall = pSmall.next;
} else {
pLarge.next = curr;
pLarge = pLarge.next;
}
curr = curr.next;
}
pLarge.next = null;
pSmall.next = large.next;
return small.next;
}
}
本文介绍了一种链表分隔算法,该算法将链表中小于给定值x的节点放置在大于等于x的节点之前,并保持各部分内部节点的原始顺序。通过创建两个辅助链表来实现这一目标,最后将这两个链表合并。
273

被折叠的 条评论
为什么被折叠?



