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 greate R than or equal to x.

You should preserve the original relative order of the nodes in each of the.

for example,
1->4->3->2->5->2  and return 1->2->2->4->3->5 .

Idea: The task of this problem is to divide the list, smaller than x of the linked list node is now larger than X or equal to the node in front, but also to maintain the original relative position do not change. We create a new two list of L1,L2, traverse the original linked list, the value is less than X nodes are added to L1, the value is greater than or equal to the X nodes are joined L2, and finally the L2 connected to the back of the L1, the resulting list is the result of our request.
  
 
  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* partition(ListNode* head, int x) {
  12. ListNode *head1,*head2;
  13. head1=head2=NULL;
  14. ListNode *cur1,*cur2;
  15. cur1=cur2=NULL;
  16. while(head){
  17. ListNode *cur=head;
  18. head=head->next;
  19. cur->next=NULL;
  20. if(cur->val<x){
  21. if(!head1){
  22. head1=cur;
  23. cur1=head1;
  24. }
  25. else{
  26. cur1->next=cur;
  27. cur1=cur1->next;
  28. }
  29. }else{
  30. if(!head2){
  31. head2=cur;
  32. cur2=head2;
  33. }else{
  34. cur2->next=cur;
  35. cur2=cur2->next;
  36. }
  37. }
  38. }
  39. if(!cur1)
  40. return head2;
  41. cur1->next=head2;
  42. return head1;
  43. }
  44. };

 

From for notes (Wiz)

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.