Lintcode96 Partition List solution题解

来源:互联网 发布:java httpclient请求 编辑:程序博客网 时间:2024/06/15 01:39

【题目描述】

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/


原创粉丝点击