86. Partition List
Posted apanda009
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了86. Partition List相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/partition-list/#/description
http://www.cnblogs.com/EdwardLiu/p/3807137.html
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
.
Analysis: Linked List 惯用套路,Runner Technique(Two Pointers), 一些技巧就是:设置head的前置假节点prev,两个pointer:current和runner都指到这个prev,然后进行判断总是判断 current.next 或者 runner.next. 这样做按照我多次做类似题的经验来说,是最方便省事不容易出错的。思路就是current 和 runner 一直移动直到找到 current.next >= x 为止,这里就是后面小于x的元素将要插入的位置,current便停在这里,指示这个位置,runner继续往后面寻找,把每一个小于x的元素都插入到current.next 的位置。
/** * 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) { return head; } ListNode dummy = new ListNode(-1); dummy.next = head; ListNode tail = dummy; ListNode pre = dummy; while (dummy.next != null && dummy.next.val < x) { dummy = dummy.next; tail = tail.next; } while (tail.next != null) { if (tail.next.val < x) { ListNode temp = tail.next; tail.next = tail.next.next; temp.next = dummy.next; dummy.next = temp; dummy = dummy.next; } else { tail = tail.next; } } return pre.next; } }
以上是关于86. Partition List的主要内容,如果未能解决你的问题,请参考以下文章