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.

  

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(head == NULL) return head;
ListNode *pre , *firstLarger, * preCur, * cur;
pre = NULL; firstLarger = head;
while(firstLarger && firstLarger->val < x){
pre = firstLarger;
firstLarger = firstLarger ->next;
}
if(firstLarger == NULL) return head; preCur = firstLarger;
cur = preCur->next; while(cur != NULL){
if( cur->val >= x){
preCur = cur;
cur = cur->next;
continue;
} preCur->next = cur->next;
cur->next = firstLarger;
if(pre == NULL){
pre = cur;
head = cur;
}else{
pre->next = cur;
pre = cur;
}
cur = preCur ->next;
} return head;
}
};

LeetCode_Partition List的更多相关文章

随机推荐

  1. tesseract-ocr图片识别开源工具

    tesseract-ocr图片识别开源工具 今天看同事的ppt,提到了图片识别,又tesseract-ocr,觉得不错,试一下,如果效果好可以用来做验证码的识别 http://code.google. ...

  2. 2013第38周日Java文件上传下载收集思考

    2013第38周日Java文件上传&下载收集思考 感觉文件上传及下载操作很常用,之前简单搜集过一些东西,没有及时学习总结,现在基本没啥印象了,今天就再次学习下,记录下自己目前知识背景下对该类问 ...

  3. MSSQL 生成有意义的PROC

    MSSQL 生成有意义的PROC --MSSQL  用PROC 生成有意义的单号:如WP200011101 GO/****** 对象:  Table [dbo].[tbl_SequenceNum]   ...

  4. [LeetCode] 148. Sort List 解题思路

    Sort a linked list in O(n log n) time using constant space complexity. 问题:对一个单列表排序,要求时间复杂度为 O(n*logn ...

  5. windows 删除服务命令

    在dos窗口下执行 sc delete  服务名( 例如 mysql) C:\Program Files\MySQL\MySQL Server 5.6\

  6. Android笔记(二):从savedIndstanceState发散

    savedIndstanceState savedIndstanceState位于ActivityonCreate(Bundle savedInstanceState)方法的参数中.对这个参数的理解要 ...

  7. solr全文检索基本原理

    场景:小时候我们都使用过新华字典,妈妈叫你翻开第38页,找到“坑爹”所在的位置,此时你会怎么查呢?毫无疑问,你的眼睛会从38页的第一个字开始从头至尾地扫描,直到找到“坑爹”二字为止.这种搜索方法叫做顺 ...

  8. (转)Maven实战(一)安装与配置

    1. 简介 Maven是基于项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具. 如果你已经有十次输入同样的Ant targets来编译你的代码.jar或者w ...

  9. monkeyrunner总结

    device=MonkeyRunner.waitForConnection()   //手机连接 result = device.takeSnapshot()    //截图 result.write ...

  10. C++11 : 外部模板(Extern Template)

    在C++98/03语言标准中,对于源代码中出现的每一处模板实例化,编译器都需要去做实例化的工作:而在链接时,链接器还需要移除重复的实例化代码.显然,让编译器每次都去进行重复的实例化工作显然是不必要的, ...