LeetCode题解-86-Partition List
2016-06-20 14:15
513 查看
原题![](http://img.blog.csdn.net/20160620141440461?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
![](http://img.blog.csdn.net/20160620144126891?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
解法1(参考别人,更简洁)
解题思路
将比X小的节点串成一串head1,将剩余的节点串成一串head2,最后将head1->head2代码
public class Solution86 {public ListNode partition(ListNode head, int x) {if (head == null || head.next == null)return head;ListNode lessHead = new ListNode(0);ListNode moreOrEqualHead = new ListNode(0);ListNode iterator = head, lessIterator = lessHead, moreOrEqualIterator = moreOrEqualHead;while (iterator != null){if (iterator.val < x){lessIterator.next = iterator;lessIterator = lessIterator.next;}else {moreOrEqualIterator.next = iterator;moreOrEqualIterator = moreOrEqualIterator.next;}iterator = iterator.next;}moreOrEqualIterator.next = null;lessIterator.next = moreOrEqualHead.next;return lessHead.next;}}
解法2
解题思路
类似冒泡排序,将比x的值小的节点从尾部“冒泡”到前方:每一次将第i个节点插入到第0个到第i个节点之间的合适的位置,插入完毕后,前i个节点符合题目要求,执行N次,结束。图解
Previous指向的为节点应该插入的位置,current节点与next节点用来判断节点是否需要移动以及存放移动时的信息。代码
public class Solution {public ListNode partition(ListNode head, int x) {if (head == null || head.next == null)return head;ListNode dummy = new ListNode(0);dummy.next = head;ListNode previous = dummy, current;while(previous.next != null && previous.next.val < x){previous = previous.next;}current = previous;while (current.next != null){ListNode next = current.next;if (current.next.val < x && current.val >= x){current.next = next.next;next.next = previous.next;previous.next = next;previous = previous.next;}else {current = current.next;}}return dummy.next;}}相关文章推荐
- 解析Java中的队列和用LinkedList集合模拟队列的方法
- 分析Java中ArrayList与LinkedList列表结构的源码
- JAVA LinkedList和ArrayList的使用及性能分析
- 浅谈 java中ArrayList、Vector、LinkedList的区别联系
- LinkedList学习示例模拟堆栈与队列数据结构
- 集合操作(一)ArrayList,LinkedList源码分析
- 关于JDK1.7中LinkedList索引方法的思考
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- 重新认识java-LinkedList
- ArrayList和LinkedList的主要区别
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum