[Leetcode] Partition List (Java)
2014-01-16 15:53
330 查看
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
把小于x的放前面,大于等于x的放后面,不改变相对顺序
只需要一个小于x元素的指针pre与大于等于x的指针post,pCur即可
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.
把小于x的放前面,大于等于x的放后面,不改变相对顺序
只需要一个小于x元素的指针pre与大于等于x的指针post,pCur即可
public class Solution { public ListNode partition(ListNode head, int x) { ListNode res = new ListNode(-1); res.next=head; ListNode pre =res; ListNode post = new ListNode(-1); ListNode pCur = post; while(head!=null){ if(head.val<x){ pre.next=head; pre=head; }else { pCur.next=head; pCur=head; } head=head.next; } pCur.next=null; pre.next=post.next; return res.next; } }
相关文章推荐
- 【LeetCode-面试算法经典-Java实现】【086-Partition List(将单链表进行分区)】
- [LeetCode][Java] Partition List
- LeetCode-JAVA-Partition List
- (Java) LeetCode 412. Fizz Buzz —— Fizz Buzz
- Leetcode-200(Java) Number of Islands
- String to Integer (atoi) leetcode java
- Merge k Sorted Lists leetcode java
- [LeetCode][Java] Climbing Stairs
- Valid Parentheses leetcode java
- [leetcode-228]Summary Ranges(java)
- leetcode解题之374. Guess Number Higher or Lower Java版 (猜数字大小二分查找)
- Simplify Path leetcode java
- 【Leetcode】:116. Populating Next Right Pointers in Each Node 问题 in JAVA
- LeetCode-282. Expression Add Operators (JAVA)表达式求值
- LeetCode-520. Detect Capital (JAVA)大写字母的合法性
- 【LeetCode刷题Java版】Reverse Words in a String
- 【LeetCode-面试算法经典-Java实现】【125-Valid Palindrome(回文字验证)】
- [Leetcode]Test1 TwoSum [java]题目分析解答
- leetcode oj java Implement Stack using Queues
- [LeetCode]-319. Bulb Switcher (Medium)(Java)