LeetCode(86) Partition List
2015-09-23 20:07
357 查看
题目
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.
分析
给定一个链表与一个目标值x,要求对链表结点按照以下要求重排:(1)值小于x的结点,按照其原顺序排列与链表头部
(3)其余值不小于x的结点,按照其原顺序链接与尾部
AC代码
class Solution { public: ListNode* partition(ListNode* head, int x) { if (!head || !head->next) return head; ListNode *p = head; head = NULL; ListNode *r = head; //(1)寻找第一个不小于目标值的节点p,前n个小于x的节点逐个连接到head,保存尾结点r while (p && p->val < x) { if (!head) { head = p; r = head; } else{ r->next = p; //保存新链表尾结点 r = r->next; } p = p->next; r->next = NULL; }//while //如果此时p为空,已经没有其余节点,返回新链表head if (!p) return head; //(2)p节点大于x,从下一个结点开始遍历,将小于x的结点连接到head中,原链表删除该结点 ListNode *pre = p , *q = p->next; while (q) { if (q->val < x) { if (!head) { head = q; r = head; } else{ r->next = q; //保存新链表尾结点 r = r->next; } pre->next = q->next; q = q->next; r->next = NULL; }//if else{ pre = q; q = q->next; }//else }//while //如果此时,原链表还剩余结点,直接连接到r后面即可 if (p) { if (!head) return p; else r->next = p; } return head; } };
GitHub测试程序源码
相关文章推荐
- Ubuntu服务器安装mysql数据库
- 【DIV+CSS】代码作业练习DIV+CSS太极阴阳图
- “新建Laravel项目”并“开启laravel”的操作
- 安卓:WebView简单使用
- UVA592字符串推断题加暴力假设搜索
- AVS2高清实时编码器问世,性能大幅超越HEVC/H.265编码器x265
- leetcode刷题,总结,记录,备忘 118
- Altium Designer 14 安装完整元件库
- Codeforces Round #321 A Kefa and First Steps
- iOS-APP发布应注意
- BaseDao的设计思路---接口编程
- Android自定义软键盘输入法,隐藏系统输入法显示光标的实现
- 优化UITableViewCell高度计算的那些事
- 高效程序员的 7 个共同特征
- poj2187(最远点的距离的平方)
- 使用Android Studio时的一个问题
- iOS-App上架流程
- xml直接读取节点
- 我公司在做什么(“paas平台”)
- Android 5.0新特性ToolBar