Leetcode "86" Partition List

Source: Internet
Author: User

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.

For example,
Given 1->4->3->2->5->2  and   x  = 3,
return< Span class= "Apple-converted-space" > 1->2->2->4->3->5 .

One idea is to find a node first, the value of the node is less than X and the node's next node value is greater than or equal to X, so that the two nodes are recorded as S and L, and then from L began to traverse the linked list, the value less than X is inserted between S and L, and update s,l does not change. The idea worth noting is that the first, the head node value is greater than X, then S is null, all nodes smaller than x are inserted into the head before the first one needs to be updated, and then S is not null; the second noteworthy is the need to update s after each insertion of SL, Otherwise, an error occurs. The AC code is as follows:

listnode* partition (listnode* head,intx) {if(!head)returnHead; //Find NodesListNode * 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)returnHead; L=s->Next; }        //search node less than x from node LListNode *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; }        }        returnHead; }

Leetcode "86" Partition List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.