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;
        }
    }
  • 相关阅读:
    个人作业——软件产品案例分析
    软件工程结对作业二
    软件工程团队展示
    软件工程第三次作业
    软件工程实践第二次作业
    软件工程实践第一次作业
    第八次课程作业
    第五次课程作业
    第四次课程作业
    wind本地MySQL数据到hive的指定路径
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10177760.html
Copyright © 2011-2022 走看看