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;
        }
    }
  • 相关阅读:
    投产包错误的思考
    Oracle----用户操作
    3.27 学习记录
    3.26 学习记录
    3.25 学习记录
    3.24 学习记录
    3. 23构建之法读后感
    3.22 学习记录
    3. 21学习记录
    3.20 学习记录
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10177760.html
Copyright © 2011-2022 走看看