Partition List
来源:互联网 发布:淘宝代码装修教程 编辑:程序博客网 时间:2024/05/27 18:17
题目描述:
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
.
模仿快排的一次排序过程即可。
注:在链表的开头加一个虚拟的节点(dummyHead)可以简化处理过程。
AC代码如下:
class Solution {public:ListNode* partition(ListNode* head, int x) {if (head == NULL) return NULL;ListNode* dummyHead1 = new ListNode(-1);ListNode* p = dummyHead1;ListNode* dummyHead2 = new ListNode(-1);dummyHead2->next = head;ListNode* q = dummyHead2;while (q->next != NULL){if (q->next->val < x){ListNode* tmp = q->next;q->next = tmp->next;p->next = tmp;p = p->next;}else{q = q->next;}}p->next = dummyHead2->next;return dummyHead1->next;}};
0 0
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Java单例模式与多线程
- 读书笔记-陆-《从你的全世界路过》
- 码神作业(九九乘法表)
- Android 6.0特性
- 递归
- Partition List
- ZYNQ Z-TURN BOARD 学习笔记1-Ubuntu上的流水灯实验
- tomcat点击startup.bat一闪而过
- HDU 5748 (Bellovin LIS)
- 随机数相关
- 欢迎使用CSDN-markdown编辑器
- CSS布局-----display,position, float属性
- 筛法和欧拉函数
- validate插件使用remote做数据唯一性校验