Partition List in C++

C++Server Side ProgrammingProgramming

Suppose we have a linked list and a value x. We have to make partitions. The partition it such that all nodes less than x comes before the nodes that are greater than or equal to x. We should preserve the original relative order of the nodes in each of these two partitions. So if the list is like [1,4,3,2,5,2] and x = 3, then the output will be [1,2,2,4,3,5]

To solve this, we will follow these steps −

  • Make dummy nodes d1 and d2, and initialize them with -1, create two pointers dp1 and dp2, they are pointing d1 and d2 respectively.
  • while a is not null
    • if value of a < b
      • next of dp1 := a new node with value of a
      • dp1 := next pointer of dp1
    • otherwise
      • next of dp2 := a new node with value of a
      • dp2 := next pointer of dp2
    • a := next of a
  • next of dp1 := next of d2
  • return next of d1

Example(C++)

Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
   public:
      int val;
      ListNode *next;
      ListNode(int data){
         val = data;
         next = NULL;
      }
};
ListNode *make_list(vector<int> v){
   ListNode *head = new ListNode(v[0]);
   for(int i = 1; i<v.size(); i++){
      ListNode *ptr = head;
      while(ptr->next != NULL){
         ptr = ptr->next;
      }
      ptr->next = new ListNode(v[i]);
   }
   return head;
}
void print_list(ListNode *head){
   ListNode *ptr = head;
   cout << "[";
   while(ptr->next){
      cout << ptr->val << ", ";
      ptr = ptr->next;
   }
   cout << "]" << endl;
}
class Solution {
public:
   ListNode* partition(ListNode* a, int b) {
      ListNode* dummy1 = new ListNode(-1);
      ListNode* dummy2 = new ListNode(-1);
      ListNode* dummyPtr1 = dummy1;
      ListNode* dummyPtr2 = dummy2;
      while(a){
         if(a->val < b){
            dummyPtr1->next = new ListNode(a->val);
            dummyPtr1 = dummyPtr1->next;
         }
         else{
            dummyPtr2->next = new ListNode(a->val);
            dummyPtr2 = dummyPtr2->next;
         }
         a = a->next;
      }
      dummyPtr1->next = dummy2->next;
      return dummy1->next;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,4,6,3,2,5,2,8};
   ListNode *head = make_list(v);
   print_list(ob.partition(head, 3));
}

Input

[1,4,6,3,2,5,2,8]
3

Output

[1, 2, 2, 4, 6, 3, 5, ]
raja
Published on 31-Jan-2020 10:44:05
Advertisements