Partition List
来源:互联网 发布:淘宝评论怎么评论内容 编辑:程序博客网 时间:2024/06/06 01:49
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的元素放在list的前面,大于等于的放在后面,其中不能打乱原来
list中元素的顺序。
我的想法是用两个queue分别存储小于x和大于等于x的元素,再分别出队列组成新的list
就是要求的list。
其实queue就是实现的linkedlist接口。九章算法直接新建两个链表分别连接小于x和大于
等于x的元素,再将小于的链表指向大于的链表,形成最后的list。
public ListNode partition(ListNode head, int x) {if (head == null) return null;ListNode leftDummy = new ListNode(0);ListNode rightDummy = new ListNode(0);ListNode left = leftDummy, right = rightDummy;while (head != null) {if (head.val < x) {left.next = head;left = head;} else {right.next = head;right = head;}head = head.next;}right.next = null;left.next = rightDummy.next;return leftDummy.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
- Ubuntu 13.10配置root登录
- Tomcat异常处理
- 黑马程序员-C语言数组的使用注意事项
- process_begin: CreateProcess(...) failed.
- 像素翻转
- Partition List
- 剑指offer 面试题4---替换空格
- 二分检索的多种应用
- 软工视频——第一章
- poj 3660 Cow Contest(warshall算法)
- SpringMvc+Spring+Mybatis 环境集成
- iOS Quartz2D - 画圆和圆弧
- 07-31 面向对象
- 计时器(Chronometer)