• 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;
        }
  • 相关阅读:
    SpringCloud_组件常用注解
    SpringBoot_启动器
    SICP习题 1.5 (应用序与正则序)
    SICP习题 1.4 ( if 语句返回运算符)
    SICP习题 1.3 (求较大两个数的递归)
    SICP习题 1.2 (前缀表达式)
    SICP习题 1.1 (if cond语句)
    MySQL5.7 踩坑实录
    类找不到总结java.lang.ClassNotFoundException
    网易校招2018----题目3----字符串碎片
  • 原文地址:https://www.cnblogs.com/ww-jin/p/4488416.html
Copyright © 2020-2023  润新知