leetcode:Partition List 【Java】
来源:互联网 发布:淘宝怎么异地发货 编辑:程序博客网 时间:2024/05/21 03:26
一、问题描述
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
.
二、问题分析
建两个链表分别保存小于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; } }}
0 0
- [Leetcode] Partition List (Java)
- [LeetCode][Java] Partition List
- leetcode:Partition List 【Java】
- LeetCode-JAVA-Partition List
- Partition List leetcode java
- [LeetCode] 86. Partition List java
- LeetCode 86(Partition List)java
- [leetcode]86. Partition List@Java解题报告
- LeetCode: Partition List
- LeetCode Partition List
- LeetCode: Partition List
- [Leetcode] Partition List **
- [Leetcode] Partition List
- [LeetCode] Partition List
- leetcode 81: Partition List
- [Leetcode] Partition List
- leetcode 118: Partition List
- [LeetCode]Partition List
- 双栈算术表达式求值算法
- 第二周项目5-个人所得税计算机
- Eclipse配置Struts2二
- linux系统ip地址的配置
- 服务端挂盘开启1394调试
- leetcode:Partition List 【Java】
- GreenDao深度探索(二)
- 快速排序的非递归写法
- Android安全教程(2)---Fiddler简易使用教程之使用
- Idiomatic Python, well format in python
- 用grunt搭建自动化的web前端开发环境
- Ubuntu下 AndroidStudio 无法识别设备(手机/平板)的问题 , 多设备可以
- 集成Cordova+crosswalk with Android
- iOS8统一的系统提示控件——UIAlertController