leetcode--Partition List
2015-06-09 17:38
323 查看
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
return
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode first = new ListNode(0);
ListNode second = new ListNode(0);
ListNode res = first;
ListNode res2 = second;
ListNode cur = head;
while(cur!=null){
if(cur.val<x){
first.next = cur;
cur = cur.next;
first.next.next = null;
first = first.next;
}else{
second.next = cur;
cur = cur.next;
second.next.next = null;
second = second.next;
}
}
first.next = res2.next;
return res.next;
}
}
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->2and x = 3,
return
1->2->2->4->3->5./**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode partition(ListNode head, int x) {
ListNode first = new ListNode(0);
ListNode second = new ListNode(0);
ListNode res = first;
ListNode res2 = second;
ListNode cur = head;
while(cur!=null){
if(cur.val<x){
first.next = cur;
cur = cur.next;
first.next.next = null;
first = first.next;
}else{
second.next = cur;
cur = cur.next;
second.next.next = null;
second = second.next;
}
}
first.next = res2.next;
return res.next;
}
}
相关文章推荐
- 数据库设计的完整性约束表现
- oracle 中存储过程无法编译。卡死, session kill 不掉。
- WebStorm下载地址及常用快捷键
- 认识自己——我需要的2
- phpExcel中文帮助手册之常用功能指南
- linux 设备文件属性
- Android数据访问存储之内存读写
- 不是语言之争--Go vs Erlang
- PHP array_combine()
- PL/SQL Developer自动补全SQL技巧
- DFS分布式文件系统
- WindowsAPI小程序
- 箭头操作符(间接运算符)arrow operator
- xtrabackup备份数据库
- TinyRMI---RMI的封装、扩展及踩到的坑的解决
- TINY框架:组件化的J2EE开发框架
- Tiny框架应用实践之Tiny社区
- 使GridView支持下拉刷新和上拉加载
- android多国语言使用
- 关于加密和解密的设计思路