zoukankan      html  css  js  c++  java
  • leetcode 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.

    For example,
    Given 1->4->3->2->5->2 and x = 3,
    return 1->2->2->4->3->5.

    题意:

    给出一个链表和一个数字x,将链表分区,小于x的都放在大于等于x的前面,而且要保持每个分区内各结点的相对位置没有发生变化。

    比如原链表中,4在3的前面,3在5的前面,分区后依然要保持这个相对位置。

    过程:

    (1)新建两个链表,一个first,一个second,

    一个用来记录链表中所有小于x的结点,一个用于记录链表中所有大于等于x的结点。

    (2)遍历原链表。

    (3)最后将两个链表连接起来作为结果返回。

    public class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head == null) return null;
            
            ListNode firstDummy = new ListNode(0);
            ListNode secondDummy = new ListNode(0);
            ListNode first = firstDummy, second = secondDummy;
            
            while(head != null){
                if(head.val < x){
                    first.next = head;
                    first = head;
                }else{
                    second.next = head;
                    second = head;
                }
                head = head.next;
            }
            
            first.next = secondDummy.next;
            second.next = null;
            return firstDummy.next;
        }
    }
  • 相关阅读:
    使用Fiddler捕获Java程序中的HTTP请求
    js解析json对象和json字符串
    写代码 在与思考
    sql 逻辑读取次数
    WbeAPI 学习笔记
    大话设计模式阅读笔记
    行转列
    sql server 的多表查询(left join )
    union 和union all比较
    sql 跨库和域插入数据库
  • 原文地址:https://www.cnblogs.com/iwangzheng/p/5714433.html
Copyright © 2011-2022 走看看