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. 【HDOJ】1497 Simple Library Management System

    链表. #include <cstdio> #include <cstring> #include <cstdlib> #define MAXM 1001 #def ...

  2. 设计模式 ( 十六 ): Mediator中介者模式 -- 行为型

    1.概述 在面向对象的软件设计与开发过程中,根据“单一职责原则”,我们应该尽量将对象细化,使其只负责或呈现单一的职责,即将行为分布到各个对象中. 对于一个模块或者系统,可能由很多对象构成,而且这些对象 ...

  3. Junit 学习

    一. 断言核心方法 示例代码: package com.test; import org.junit.Assert; import org.junit.Test; /** * @Title: test ...

  4. JS-string内置对象

    1.charCodeAt方法返回一个整数,代表指定位置字符的Unicode编码. strObj.charCodeAt(index) 说明: index将被处理字符的从零开始计数的编号.有效值为0到字符 ...

  5. MarkWord - 可发布博客的 Markdown编辑器 代码开源

    因为前一段时间看到 NetAnalyzer 在Windows10系统下UI表现惨不忍睹,所以利用一段时间为了学习一下WPF相关的内容,于是停停写写,用了WPF相关的技术,两个星期做了一个Markdow ...

  6. HDU 1015 Safecracker 解决问题的方法

    Problem Description === Op tech briefing, 2002/11/02 06:42 CST ===  "The item is locked in a Kl ...

  7. Python进阶之路---1.5python数据类型-字符串

    字符串 *:first-child { margin-top: 0 !important; } body>*:last-child { margin-bottom: 0 !important; ...

  8. Universal-Image-Loader 示例 工具

    Base public class MyApplication extends Application {     @Override     public void onCreate() {     ...

  9. 小学生之KTV项目文档(bdqn)

    第一步:创建数据库连接方法和打开方法和关闭方法! 1 public class DBHelper 2 { 3 private string str = "server=.;database= ...

  10. SSAS数据集Cube不存在或者尚未处理

    对Microsoft SQL Server(2008) Analysis Services(以下称SSAS) 多维数据集运行多维表达式 (MDX) 查询时,会返回这个错误消息:XXX Cube不存在, ...