zoukankan      html  css  js  c++  java
  • Partition List

    description:

    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.

    thoughts:
    我们创建两个链表,第一个链表用来记录小于x的listnode,另一个链表用来记录大于等于x的listnode,然后将前一个链表的尾指针之下第二个两遍,实现两个链表的merge。

    以下是java代码:

    package middle;
    
    class ListNode{
        int val;
        ListNode next;
        ListNode(int x){
            val = x;
        }
    }
    
    public class PartitionList {
        public ListNode partition(ListNode head, int x){
            ListNode dumy1 = new ListNode(0);
            ListNode dumy2 = new ListNode(0);
            ListNode cur1 = dumy1;
            ListNode cur2 = dumy2;
            while(head!=null){
                if(head.val < x){
                    cur1.next = head;
                    cur1 = cur1.next;
                }else{
                    cur2.next = head;
                    cur2 = cur2.next;
                }
                head = head.next;
            }
            cur2.next = null;
            cur1.next = dumy2.next;
            return dumy1.next;
        }
        public static void main(String[] args){
            PartitionList p = new PartitionList();
            int x = 5;
            ListNode head = new ListNode(0);
            ListNode tail = head;
            for(int i = 0;i<5;i++){
                ListNode tempNode = new ListNode(i);
                head.next = tempNode;
                head = head.next;
            }
            head.next = null;
            p.partition(tail, x);
            while(tail != null){
                System.out.println(tail.val);
                tail = tail.next;
            }
        }
        
    }
  • 相关阅读:
    彻底弄懂flex布局
    剖析Vue原理&实现双向绑定MVVM
    【Mysql进阶-3】大量实例悟透EXPLAIN与慢查询
    mysql 排序
    从ReentrantLock的实现看AQS的原理及应用
    Java面试之Synchronized解析
    基于vue-cli搭建vue项目开发环境
    在win环境下使用yarn安装 vue-cli
    优化器追踪示例
    MySQL常见的七种锁详细介绍
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7542107.html
Copyright © 2011-2022 走看看