[LeetCode]Partition List, 解题报告
2014-01-17 21:53
351 查看
题目
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的节点移到前面解法:我们可以构建两个链表,一个链表存放所有小于x的节点,另一个链表存放所有大于x的节点,然后连接两个链表即可
AC代码
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode partition(ListNode head, int x) { ListNode smaller, bigger, tmps, tmpb; smaller = new ListNode(0); tmps = smaller; bigger = new ListNode(0); tmpb = bigger; while (head != null) { if (head.val < x) { tmps.next = head; tmps = head; } else { tmpb.next = head; tmpb = head; } head = head.next; } tmpb.next = null; tmps.next = bigger.next; return smaller.next; } }
相关文章推荐
- CentOS下InfiniBand驱动安装过程
- infopath2007-2013直接连接数据源(Access或Sqlserver)设计表单模板
- My App Crashed, Now What? – Part 1
- -----log4c日志库在Linux中的使用 -------------
- poj 2031 Building a Space Station(最小生成树,三维,基础)
- js入门例子小结2
- ruby连接redis
- web前端积累
- Handler 的执行原理----底层代码
- MVC-READ1
- poj 3728 The merchant(tarjan求lca)
- learning nodejs 1 - stream.pipe
- C++引言
- hdu 1081To The Max(二维最大连续子串和)
- cocos2d-x与ISO内存管理
- 并发和并行的区别
- c语言gmail基于openssl的简易程序
- 题目1096:日期差值
- CocoaPods安装和使用教程
- SignalR中获取cookie的解决方法