[Leetcode] 86. Partition List Problem Solving ideas

Source: Internet
Author: User

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greate R 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 1->2->2->4->3->5 .

Issue: Given a list and integer x, move all elements in the list that are less than x to the front of an element that is greater than or equal to X. Requires that the elements of the interior of the second part of the move are in the same relative position as the original.

When you see the topic, you need to divide a column number into two parts less than X and greater than or equal to X, the first thought is to use two pointers from the two paragraphs to the middle sweep to solve. However, the topic is a list, cannot be swept forward from the back, and the relative position after the move to save and before the same, you cannot use this method.

The second idea is to store the new list order in an array, and then establish a pointer relationship between the elements in the array. This idea is relatively simple, also submitted through.

1listnode* partition (listnode* head,intx) {2         3         if(Head = =NULL) {4             returnNULL;5         }6             7Vector<listnode*>arr;8         9listnode* tmp =head;Ten          while(TMP! =NULL) { One              A             if(Tmp->val <x) { - Arr.push_back (TMP); -             } the  -TMP = tmp->Next; -         } -          +TMP =head; -          while(TMP! =NULL) { +              A             if(x <= tmp->val) { at Arr.push_back (TMP); -             } -              -TMP = tmp->Next; -         } -              in          for(inti =0; I < arr.size ()-1; i++) { -Arr[i]->next = arr[i+1]; to         } +Arr[arr.size ()-1]->next =NULL; -          theHead = arr[0]; *          $         returnhead;Panax Notoginseng          -}

[Leetcode] 86. Partition List Problem Solving ideas

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.