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并且该节点的next节点的值大于等于x,这样的两个节点分别记为S和L,然后从L开始遍历链表,将小于x的值插入到S和L之间,并且更新S,L并不改变。这个想法值得注意的几点,第一个,head节点的值就大于x,则S为NULL,所有比x小的节点都要插入到Head之前,当插入第一个之后需要更新头节点,此后S不为NULL;第二个值得注意的就是每次插入SL之间后,需要更新S,否则出错。AC代码如下:

    ListNode* partition(ListNode* head, int x) {
            if(!head)
                return head;
            //find two nodes
            ListNode * s=head;
            ListNode * l=NULL;
            if(head->val >= x)
            {
                l = head;
                s = NULL;
            }
            else
            {
                while(s->next!=NULL && s->next->val <x )
                    s=s->next;
                if(s->next == NULL)
                    return head;
                l=s->next;
            }
            //search node less than x from node L
            ListNode *fir=l;
            ListNode *sec=fir->next;
            for(;sec!=NULL;)
            {
                if(fir->val>=x && sec->val < x)
                {
                    fir->next = sec->next;
                    if(s)
                    {
                        s->next = sec;
                        sec->next = l;
                        s= sec;
                    }
                    else
                    {
                        sec->next = l;
                        head = sec;
                        s= sec;
                    }
                    sec = fir->next;
                }
                else
                {
                    fir = fir->next;
                    sec = sec->next;
                }
            }
            return head;
        }
  • 相关阅读:
    Visual GC(监控垃圾回收器)
    垃圾收集(GC)中如何确定哪些内存是"垃圾
    Java for循环和foreach循环的性能比较
    <mvc:annotation-driven />做了什么
    聊一聊分布式锁的设计
    String类对象的比较
    Java 中 Comparable 和 Comparator 比较
    系统对接API调用
    深入理解Java中的组合和继承
    面向对象设计七大原则
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4488416.html
Copyright © 2011-2022 走看看