zoukankan      html  css  js  c++  java
  • 86. Partition List

    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

    用两个dummy head,两个dummy tail,分别表示<=x的,和>x的,然后把两个list首尾相连。最后记得把larger list的末尾指向null,防止出现cycle

    time: O(n), space: O(1)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head == null || head.next == null) {
                return head;
            }
            ListNode dummyHeadSmall = new ListNode(0);
            ListNode dummyHeadLarge = new ListNode(0);
            ListNode dummyTailSmall = dummyHeadSmall;
            ListNode dummyTailLarge = dummyHeadLarge;
            
            ListNode cur = head;
            while(cur != null) {
                if(cur.val < x) {
                    dummyTailSmall.next = cur;
                    dummyTailSmall = dummyTailSmall.next;
                } else {
                    dummyTailLarge.next = cur;
                    dummyTailLarge = dummyTailLarge.next;
                }
                cur = cur.next;
            }
            dummyTailSmall.next = dummyHeadLarge.next;
            dummyTailLarge.next = null;
            return dummyHeadSmall.next;
        }
    }
  • 相关阅读:
    MVC常用跳转页面的方法
    简单工厂模式
    MySQL 查询昨天中午12点到今天中午12点的数据
    Windows安装yarn
    MapStruct
    CSS 3D
    05-序列化器ModelSerializer
    django基础之Django中间件
    04-序列化器Serializer
    03-四大基本模块
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10177760.html
Copyright © 2011-2022 走看看