[LeetCode] 86. Partition List

发布时间:2019-07-27 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode] 86. Partition List脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Problem

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.

Example:

Input: head = 1->4->3->2->5->2, x = 3
Output: 1->2->2->4->3->5

Solution

class Solution {
    public ListNode partition(ListNode head, int x) {
        ListNode dummy1 = new ListNode(0);
        ListNode dummy2 = new ListNode(0);
        ListNode small = dummy1, large = dummy2;
        while (head != null) {
            if (head.val < x) {
                small.next = head;
                small = small.next;
            } else {
                large.next = head;
                large = large.next;
            }
            head = head.next;
        }
        small.next = dummy2.next;
        large.next = null;
        return dummy1.next;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode] 86. Partition List全部内容,希望文章能够帮你解决[LeetCode] 86. Partition List所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: