题目:

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小的节点按顺序连成一条链,比x大或等于的节点连成另一条链,然后把两条链连起来。注意一下边界情况(某条链为空)。

/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @param {number} x
* @return {ListNode}
*/
var partition = function(head, x) {
if(head==null||head.next==null){
return head;
}
var lHead=null;
var gHead=null; var p=head,pl=null,pg=null,temp=null; while(p){
if(p.val<x){
if(lHead==null){
lHead=p;
pl=p;
}else{
pl.next=p;
pl=pl.next;
}
}else{
if(gHead==null){
gHead=p;
pg=p;
}else{
pg.next=p;
pg=pg.next;
}
}
temp=p;
p=p.next;
temp.next=null;
} if(pg!=null){
pg.next=null;
}
if(lHead!=null){
pl.next=gHead;
return lHead;
}else{
return gHead;
}
};

最新文章

  1. JavaScript类属性
  2. append追加的使用
  3. 廖雪峰js教程笔记11 操作DOM(包含作业)
  4. bss段和data段的区别
  5. mysql之消息队列
  6. [转]android Intent机制详解
  7. 【HTML】心愿墙 Demo展示
  8. CentOS5.5 下编译安装 LAMP
  9. NSDate 的一些操作(比较、创建、在现有date加减一定时间等)
  10. BZOJ 1832: [AHOI2008]聚会( LCA )
  11. c#重命名文件,报错“System.NotSupportedException”类型的未经处理的异常在 mscorlib.dll 中发生”
  12. 解析ArcGis拓扑——检查的流程,以面重叠检查为例
  13. shell 写的 jrottenberg/ffmpeg 转码
  14. 招中高级web开发工程师
  15. nmon监控数据分析
  16. SSM-网站后台管理系统制作(1)
  17. 查看,设置,设备的 竖屏-横屏模式 screen.orientation
  18. 使用MVCPager做AJAX分页所需要注意的地方
  19. centos openvpn 安装
  20. 无法加载 DLL“ParkCOM.dll”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E) 终结者

热门文章

  1. LA 3708 &amp;&amp; POJ 3154 Graveyard (思维)
  2. 使用WinSCP在Windows和Linux系统之间传输文件
  3. HDU 3472 混合图欧拉回路 + 网络流
  4. Ansible免密码登陆
  5. Eclipse代码提示功能设置
  6. Asp.net Core2.0, 基于 claims 实现权限验证
  7. think in java 手记(一)
  8. 微信Web APP应用
  9. 疑难杂症--SQL SERVER 2012下数据库内存异常回收
  10. SinGooCMS 内容管理系统