zoukankan      html  css  js  c++  java
  • 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节点的前面。。

    正常思路就行:新建两个链表,一个存放大于x的,一个存放小于x的。最后连接起来。注意写代码的一些细节。最后节点(大链表的最后一个)的next要设为null

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    class Solution {
        public ListNode partition(ListNode head, int x) {
            if(head==null||head.next==null) return head;
            ListNode small=new ListNode(0);
            ListNode big=new ListNode(0);
            ListNode s=small,b=big;  //用来遍历添加节点
            while(head!=null){
                if(head.val>=x){
                    b.next=head;
                    b=b.next;
                }else{
                    s.next=head;
                    s=s.next;
                }
                head=head.next;
            }
            b.next=null;   //大的最后一个节点的next要设为null,这一步一定不能忘记。不然它还是会指向原来的next。
            s.next=big.next;
            return small.next;
        }
    }
  • 相关阅读:
    [转载]kafka分布式消息机制
    mysql partition(mysql range partition,对历史数据建分区)
    【转载】MySQL Show命令总结
    【转载】hive优化之一
    【转载】SQL必知必会点
    先行发生原则Happens-before
    指令重排序
    并发编程常见面试题
    CAS无锁机制
    锁机制
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8214236.html
Copyright © 2011-2022 走看看