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