leetcode: Partition List
来源:互联网 发布:python 记录访客数据 编辑:程序博客网 时间:2024/05/20 15: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.
For example,
Given 1->4->3->2->5->2
and x = 3,
return 1->2->2->4->3->5
.
非常机智的实现,因为需要是稳定的,所以保持相对位置不变,设置两个dummy头结点分别维护val小于x的节点和大于等于x的节点,最后连接两个链表
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode *partition(ListNode *head, int x) { if( head == NULL) return head; ListNode dummy_less(INT_MIN);//设置两个dummy节点方便实现 ListNode dummy_greater(INT_MIN); auto less_cur = &dummy_less;//指向两个dummy节点的指针 auto greater_cur = &dummy_greater; for( ListNode *cur = head; cur; cur = cur->next){ if( cur->val < x){ less_cur->next = cur; less_cur = less_cur->next; } else{ greater_cur->next = cur; greater_cur = greater_cur->next; } } less_cur->next = dummy_greater.next;//链接两个链表 greater_cur->next = NULL; return dummy_less.next; }};
0 0
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- [leetcode]Partition List
- LeetCode-Partition List
- [leetcode] Partition List
- LeetCode - Partition List
- [LeetCode] Partition List
- LeetCode 86: Partition List
- LeetCode:Partition List
- 【leetcode】Partition List
- 短语in all likelihood
- 声明与定义&&赋值与初始化详解
- 利用MessageSource实现国际化[I18N]
- Python编程-matplotlib3D直方图绘制
- 鱼腥与香囊
- leetcode: Partition List
- cocos2d-x游戏项目初始阶段控制权转移过程
- Linux i2c设备驱动编写(二)
- resin 出现大量CLOSE_WAIT 状态
- 带头像的用户注册页面
- CentOS 系统中Mysql数据库卸载、安装与配置教程
- 关于使用key/value数据库redis和TTSERVER的心得体会
- [Serializable]关键字
- openSUSE:Packaging checks