Divide the given linked list in two lists of size ratio p:q in C++ Program


In this tutorial, we are going to write a program that divides the given linked list into a p:q ratio

It's a straightforward program. Let's see the steps to solve the problem.

  • Create a struct for the linked list node.

  • Initialize the linked list with dummy data.

  • Initialize the p:q ratio.

  • Find the length of the linked list.

  • If the length of the linked list is less than p + q, then it's not possible to divide the linked into a p:q ratio.

  • Else iterate the linked list until p.

  • After the p iterations, remove the link and create a new head for the second linked list.

  • Now, print the two parts of the linked list.

Example

Let's see the code.

 Live Demo

#include<bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   Node *next;
   Node(int data) {
      this->data = data;
      this->next = NULL;
   }
};
void printLinkedList(Node* head) {
   Node *temp = head;
   while (temp) {
      cout << temp->data << " -> ";
      temp = temp->next;
   }
   cout << "NULL" << endl;
}
void splitLinkedList(Node *head, int p, int q) {
   int n = 0;
   Node *temp = head;
   // finding the length of the linked list
   while (temp != NULL) {
      n += 1;
      temp = temp->next;
   }
   // checking wether we can divide the linked list or not
   if (p + q > n) {
      cout << "Can't divide Linked list" << endl;
   }
   else {
      temp = head;
      while (p > 1) {
         temp = temp->next;
         p -= 1;
      }
      // second head node after splitting
      Node *head_two = temp->next;
      temp->next = NULL;
      // printing linked lists
      printLinkedList(head);
      printLinkedList(head_two);
   }
}
int main() {
   Node* head = new Node(1);
   head->next = new Node(2);
   head->next->next = new Node(3);
   head->next->next->next = new Node(4);
   head->next->next->next->next = new Node(5);
   head->next->next->next->next->next = new Node(6);
   int p = 2, q = 4;
   splitLinkedList(head, p, q);
}

Output

If you run the above code, then you will get the following result.

1 -> 2 -> NULL
3 -> 4 -> 5 -> 6 -> NULL

Conclusion

If you have any queries in the tutorial, mention them in the comment section.

Updated on: 28-Jan-2021

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements