leetcode:Partition List 【Java】
2016-03-11 17:04
239 查看
一、问题描述
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
二、问题分析
建两个链表分别保存小于target的值和大于target的值。
在建新链表的过程中需要打断原链表中的链。
三、算法代码
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->2and x = 3,
return
1->2->2->4->3->5.
二、问题分析
建两个链表分别保存小于target的值和大于target的值。
在建新链表的过程中需要打断原链表中的链。
三、算法代码
/** * 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) { if(head == null || head.next == null){ return head; } ListNode lesser = null, lesserHead = null; ListNode greater = null, greaterHeader = null; ListNode cur = null; if(head.val < x){ lesserHead = head; lesser = head; cur = head.next; lesser.next = null;//打断原链表中的链 }else{ greaterHeader = head; greater = head; cur = head.next; greater.next = null;//打断原链表中的链 } while(cur != null){ if(cur.val < x){ if(lesserHead == null){ lesserHead = cur; lesser = cur; cur = cur.next; lesser.next = null;//打断原链表中的链 }else{ lesser.next = cur; lesser = lesser.next; cur = cur.next; lesser.next = null; //打断原链表中的链 } }else{ if(greaterHeader == null){ greaterHeader = cur; greater = cur; cur = cur.next; greater.next = null;//打断原链表中的链 }else{ greater.next = cur; greater = greater.next; cur = cur.next; greater.next = null;//打断原链表中的链 } } } if(lesserHead == null){ return greaterHeader; }else{ lesser.next = greaterHeader; return lesserHead; } } }
相关文章推荐
- Spring使用c3p0数据源
- java 模仿原版坦克大战
- java设计模式——结构型之适配器模式
- CXF+Spring 发布SOAP服务
- java工具类小知识
- [Java代码] Java 面向对象
- Eclipse 使用配置记录,快捷键
- [Java代码] Java排序算法之——希尔排序
- Eclipse中配置Struts2
- Spring+WebSocket整合(SSM)
- SpringMVC - 页面form表单绑定对象
- java中的闭包
- java 的3DES解密和加密
- Java_Iterable_Iterator_foreach学习笔记
- spark.driver.maxResultSize || java.lang.OutOfMemoryError
- SVN--(Eclipse)在历史记录中比较版本差异
- java的if-else和while用法
- 使用java反射机制对类字段进行选择性校验示例
- Java_移位运算
- Java常用类库--观察者设计模式( Observable类Observer接口)