Given a linked list and two integers p and q, the task is to divide the linked list in the ratio p:q i.e. the first list contains first p nodes from the original list and the second list contains the rest of the q nodes. If the original list cannot be split in the given ratio then print -1.
Input: 1 -> 3 -> 5 -> 6 -> 7 -> 2 -> NULL
p = 2, q = 4
5 6 7 2
Input: 1 -> 2 -> 4 -> 9 -> NULL
p = 3, q = 2
Approach: First find the length of the linked list. If the total ratio sum exceeds the actual length then dividing the list is not possible so print -1. If it is possible to divide the list then simply traverse the list up to length p and break it into the ratio p:q. Next node will be the head of the second list then print both the lists.
Below is the implementation of the above approach:
1 3 5 6 7 2
Time Complexity: O(n)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Create a linked list from two linked lists by choosing max element at each position
- Create new linked list from two given linked list with greater element at each node
- Merge two sorted linked lists such that merged list is in reverse order
- In-place Merge two linked lists without changing links of first list
- Multiply two numbers represented as linked lists into a third list
- Merge two unsorted linked lists to get a sorted list
- Generate Linked List consisting of maximum difference of squares of pairs of nodes from given Linked List
- Count pairs from two linked lists whose sum is equal to a given value
- Count pairs from two linked lists whose product is equal to a given value
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
- Difference between Singly linked list and Doubly linked list
- Convert Singly Linked List to XOR Linked List
- Check if a linked list is Circular Linked List
- Compare two strings represented as linked lists
- Subtract Two Numbers represented as Linked Lists
- Union and Intersection of two linked lists | Set-2 (Using Merge Sort)
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.