• 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;
            
        }
    }
  • 相关阅读:
    JDBC批量删除某一用户下的触发器
    DWZ框架修改默认主页(转)
    JSP页面中的js方法遍历后台传来的自定义对象的List
    JDBC获取表注释
    你的显示方式安全么?JSTL中c:out标签介绍
    tomcat启动报错
    PPP协议体系的实现
    Linux下的虚拟Bridge实现
    三皇五帝
    贴近原理层的科技发展
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/5976520.html
Copyright © 2020-2023  润新知