Partition List
来源:互联网 发布:经销商车销软件 编辑:程序博客网 时间:2024/05/22 11:31
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
.
思路:
这道题要求将一个链表重新排列,其中元素小于k的在前面,大于等于k的在后面。
如果在原链表上操作会把原链表搞的支零破碎,非常麻烦。如果能过想到构造出两个新的链表,那题目的难度会降低很多。
一个链表用来存储小于k的元素,另一个链表用于存储大于k的元素,在将所有元素存储完毕之后,将两个链表拼接在一起就大功告成了。
public class PartitionList { public ListNode partition(ListNode head, int x) { if(head == null || head.next == null) return head; ListNode dummy1 = new ListNode(0); ListNode dummy2 = new ListNode(0); ListNode cur1 = dummy1; ListNode cur2 = dummy2; while(head != null) { if(head.val < x) { cur1.next = new ListNode(head.val); cur1 = cur1.next; } else { cur2.next = new ListNode(head.val); cur2 = cur2.next; } head = head.next; } cur1.next = dummy2.next; return dummy1.next; }}
阅读全文
0 0
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- Partition List
- 图案拉长字体发光
- Java api中文在线版
- JAVA设计模式之抽象工厂模式
- attention model
- 日期+序列构建系统唯一序列号(一)
- Partition List
- 过渡(Transition)面积大小切换
- Vue项目 其他
- java.lang.Object[] java.util.Collection.toArray()
- gradle管理javaweb项目配置仓库,解决依赖下载龟速
- web
- UVA 10815 【set的使用】【字符串模拟】
- matlab数据挖掘学习篇----数据特征分析
- map + 启发式合并