zoukankan      html  css  js  c++  java
  • Leetcode 4——Partition List

    Problems:

    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

      实现一个patition()方法,里面两个参数,一个链表,一个数字,要求把链表中小于该数字和大于等于该数字的值按照原顺序形成一个新链表。

      其实这是一个比较简单的题目,但是对于从头开始学编程的我用了两次就A掉了,还是比较高兴的,虽然这个程序的效率不是很高,哈哈。

      用两个数组存其中的大小数,然后分别放到链表里面就好了。

    Solution:

    /**
     * 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) {
            ListNode l3=head;
            int n=0;
            while(l3!=null)
            {
                l3=l3.next;
                n++;
            }
            
            l3=head;
            int[] a=new int[n];
            int[] b=new int[n];
            int small=0,big=0;
            while(l3!=null)
            {
                if(l3.val<x)
                {
                    a[small]=l3.val;
                    small++;
                    l3=l3.next;
                }
                else
                {
                    b[big]=l3.val;
                    big++;
                    l3=l3.next;
                }
            }
            
            for(int i=0;i<small;i++)
            {   
                
                if(i==0)
                {
                    l3=new ListNode(a[i]);
                    head=l3;
                }
                else 
                {
                    l3.next=new ListNode(a[i]);
                    l3=l3.next;
                }
            }
            for(int i=0;i<big;i++)
            {   
                if(small==0)
                {
                    l3=new ListNode(b[i]);
                    head=l3;
                    small=1;
                    continue;
                }
                
                l3.next=new ListNode(b[i]);
                l3=l3.next;
                
                if(i==big-1)
                {
                    l3.next=new ListNode(b[i]);
                    l3.next=null;
                }
            }
            return head;
        }
    }
  • 相关阅读:
    Spring Cloud
    如何修改容器时间而不改变宿主机时间?
    消息中间件 RabbitMQ 入门篇
    CentOS7下NFS服务安装及配置固定端口
    查看ssh有没有被黑的IP
    JVM常用命令和性能调优建议
    nfs高可用
    kafka集群部署以及单机部署
    OSGI企业应用开发(十三)OSGI Web应用开发(二)
    OSGI企业应用开发(十二)OSGI Web应用开发(一)
  • 原文地址:https://www.cnblogs.com/GoForMyDream/p/6130351.html
Copyright © 2011-2022 走看看