博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[LeetCode] Partition List 划分链表
阅读量:7096 次
发布时间:2019-06-28

本文共 1877 字,大约阅读时间需要 6 分钟。

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.

这道题要求我们划分链表,把所有小于给定值的节点都移到前面,大于该值的节点顺序不变,相当于一个局部排序的问题。那么可以想到的一种解法是首先找到第一个大于或等于给定值的节点,用题目中给的例子来说就是先找到4,然后再找小于3的值,每找到一个就将其取出置于4之前即可,代码如下:

解法一

class Solution {public:    ListNode *partition(ListNode *head, int x) {        ListNode *dummy = new ListNode(-1);        dummy->next = head;        ListNode *pre = dummy, *cur = head;;        while (pre->next && pre->next->val < x) pre = pre->next;        cur = pre;        while (cur->next) {            if (cur->next->val < x) {                ListNode *tmp = cur->next;                cur->next = tmp->next;                tmp->next = pre->next;                pre->next = tmp;                pre = pre->next;            } else {                cur = cur->next;            }        }        return dummy->next;    }};

这种解法的链表变化顺序为:

1 -> 4 -> 3 -> 2 -> 5 -> 2 

1 -> 2 -> 4 -> 3 -> 5 -> 2 

1 -> 2 -> 2 -> 4 -> 3 -> 5

此题还有一种解法,就是将所有小于给定值的节点取出组成一个新的链表,此时原链表中剩余的节点的值都大于或等于给定值,只要将原链表直接接在新链表后即可,代码如下:

解法二

class Solution {public:    ListNode *partition(ListNode *head, int x) {        if (!head) return head;        ListNode *dummy = new ListNode(-1);        ListNode *newDummy = new ListNode(-1);        dummy->next = head;        ListNode *cur = dummy, *p = newDummy;        while (cur->next) {            if (cur->next->val < x) {                p->next = cur->next;                p = p->next;                cur->next = cur->next->next;                p->next = NULL;            } else {                cur = cur->next;            }        }        p->next = dummy->next;        return newDummy->next;    }};

 本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。

你可能感兴趣的文章
勤快的love枫[ZJOI2007]
查看>>
Linux查看系统信息的一些命令及查看已安装软件包的命令
查看>>
poj1417 true liars(并查集 + DP)详解
查看>>
离散数学--二元关系总结
查看>>
HTML5 本地存储 localStorage、sessionStorage 的遍历、存储大小限制处理
查看>>
【leetcode】688. Knight Probability in Chessboard
查看>>
【leetcode】Maximum Product of Word Lengths
查看>>
C 工具库 GLib --- 提供多种高级的数据结构,如内存块、双向和单向链表、哈希表、动态字符串等...
查看>>
SQL中format()函数对应的格式
查看>>
svn command
查看>>
职业插画之路
查看>>
Java入门篇(五)——字符串/String类
查看>>
python 的StringIO
查看>>
第三个阶段事后诸葛亮
查看>>
java中的sql语句中如果有like怎么写
查看>>
【原创】驱动加载之StartService
查看>>
1751: [Usaco2005 qua]Lake Counting
查看>>
【BZOJ】4753: [Jsoi2016]最佳团体 01分数规划+树上背包
查看>>
iOS 获取设备信息之UIDevice的使用,Swift 基于 API
查看>>
IntelliJ cannot log in to GitHub上传github报错解决
查看>>