LeetCode----- 86.Partition List
来源:互联网 发布:哪个软件可以写日记 编辑:程序博客网 时间:2024/04/29 23:05
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的节点之前。您应该保留两个分区中的每一个节点的原始相对顺序。
思路:构造两个新的链表less,more,将小于x值的节点依次插入到less链表,将大于x值的节点依次到more链表。最后more链表的最后一个节点指向null,并且将more链表插入到less链表的后面。
代码如下:
public class PartitionList {public static ListNode partition(ListNode head, int x) {if(head == null || head.next == null ) {return head;}ListNode less = new ListNode(0);ListNode more = new ListNode(0);ListNode node = head,pre = less,front = more;while(node != null) {if(node.val < x) {pre.next= node;pre = pre.next;}else {front.next = node;front = front.next;}node = node.next;}front.next = null;pre.next = more.next;return less.next;}public static void main(String[] args) {ListNode l10 = new ListNode(1);ListNode l11 = new ListNode(2);ListNode l12 = new ListNode(3);ListNode l13 = new ListNode(2);ListNode l14 = new ListNode(5);ListNode l15 = new ListNode(2);l10.next = l11;l11.next = l12;l12.next = l13;l13.next = l14;l14.next = l15;l15.next = null;ListNode node = partition(l10,3);while(node != null) {if(node.next == null) {System.out.println(node.val);}else{System.out.print(node.val +"->");}node = node.next;}}}
阅读全文
0 0
- [LeetCode]86.Partition List
- LeetCode 86. Partition List
- [Leetcode] 86. Partition List
- LeetCode --- 86. Partition List
- [leetcode] 86.Partition List
- [leetcode] 86. Partition List
- [LeetCode]86. Partition List
- 86. Partition List LeetCode
- Leetcode 86. Partition List
- LeetCode *** 86. Partition List
- LeetCode 86. Partition List
- [LeetCode]86. Partition List
- LeetCode 86. Partition List
- leetcode 86. Partition List
- Leetcode 86. Partition List
- LeetCode-86.Partition List
- [Leetcode]86. Partition List
- LeetCode - 86. Partition List
- eclipse编译错误
- C语言作业
- struts2 和ajax整合使用案例(原生态的ajax操作 和 struts2和ajax整合操作)
- layui 复选框等内置控件不显示问题
- Linux usb子系统(一) _写一个usb鼠标驱动
- LeetCode----- 86.Partition List
- Servlet详解(二)
- sqlite API
- Python之format函数
- linux删除回收站
- linux基本命令
- 敏捷设计简单说明
- Hadoop完全分布式安装
- [初学笔记] matlab中eval,evalin,evalc的用法