# 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;
}
};
while (temp) {
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL" << endl;
}
int n = 0;
// 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 {
while (p > 1) {
temp = temp->next;
p -= 1;
}
// second head node after splitting
temp->next = NULL;
}
}
int main() {
int p = 2, q = 4;
}

## 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

73 Views