zoukankan      html  css  js  c++  java
  • leetcode 86 Partition List ----- java

    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.

    将一个链表划以x为界限划分为两部分,左边小于x,右边的大于等于x,两边的顺序相对不变。

    解法比较简单,没有什么特殊的技巧,分别记录左边和右边的节点即可。

    主要是注意最后要让右边的结尾 List2.next = null,否则可能会成环。

    比如[2,1],k=2时,如果不加 List2.next = null ,就会成环。

    /**
     * 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 || head.next == null)
                return head;
            ListNode List1 = new ListNode(0);
            ListNode List2 = new ListNode(0);
            ListNode result = List1;
            ListNode ll = List2;
            ListNode flag = head;
            while( flag != null){
                if( flag.val < x){
                    List1.next = flag;
                    List1 = List1.next;
                }else{
                    List2.next = flag;
                    List2 = List2.next;
                }
                flag = flag.next;
            }
            List2.next = null;
            List1.next = ll.next;
            return result.next;
            
        }
    }
  • 相关阅读:
    Codeforces Round #174 (Div. 1 + Div. 2)
    Codeforces Round #176 (Div. 1 + Div. 2)
    [ARC101C] Ribbons on Tree 解题报告
    [CTS2019]珍珠 解题报告
    CF1349D Slime and Biscuits 解题报告
    [PKUWC2018]猎人杀 解题报告
    AGC047 解题报告
    肯德基 解题报告
    [GXOI/GZOI2019]旧词 解题报告
    [ARC084B] Small Multiple 解题报告
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5976520.html
Copyright © 2011-2022 走看看