【题目描述】
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.
给定一个单链表和数值x,划分链表使得所有小于x的节点排在大于等于x的节点之前。
你应该保留两部分内链表节点原有的相对顺序。
【题目链接】
www.lintcode.com/en/problem/partition-list/
【题目解析】
可将整个链表先分离为两个小的链表。
我们建立less和greater,分别存储小于x的元素和不小于x的元素。遍历原链表,将其中的元素根据其val分别加入对应的链表。最后将less的最后一个元素与greater的链表头相连即可。
需要注意的是,若less链表为空,则应该返回greater链表的头。
【参考答案】
www.jiuzhang.com/solutions/partition-list/
转载于:https://blog.51cto.com/13107314/1978479
本文介绍了一种链表分区算法,该算法能够有效地将链表中小于特定值x的节点放置在大于等于x的节点之前,并保持各部分内部节点的原始顺序不变。通过创建两个辅助链表分别收集小于x和不小于x的节点,最后将这两个链表连接起来形成最终的分区链表。
2590

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



