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.
Example:
Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5
思路1
- 使用
before_head链表存放比x小的节点,after_head链表存放比x大于或等于的节点, - 分别使用
before和after来为前面两个链表添加节点,用head来遍历原始链表。 - 当原始链表遍历完成时,我们需要将
before_head链表连接上after_head链表,即before->next=after_head->next;after->next=NULL; - 初始化两个指针
before和after。在实现中,我们将两个指针初始化为哑结点(空的头结点)ListNode
时间复杂度: O(N)O(N)O(N) 空间复杂度:O(1)O(1)O(1)
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-guf7lwb0-1586619598582)(https://i.loli.net/2020/04/06/UKn9HpFNVhweSxE.png)]
代码1
本文介绍了一种链表分隔算法,该算法可以将链表中的节点根据给定的值x进行分隔,使得所有小于x的节点位于大于或等于x的节点之前,同时保持各分区内的相对顺序不变。通过使用两个辅助链表分别收集小于x和大于等于x的节点,最后将两部分链接起来,实现O(N)时间复杂度和O(1)空间复杂度。
590

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



