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)
- 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
- Reverse a Linked List according to its Size
- Multiply two numbers represented as linked lists into a third list
- Reverse a Linked List in groups of given size | Set 1
- Reverse a Linked List in groups of given size | Set 2
- In-place Merge two linked lists without changing links of first list
- Program to find size of Doubly Linked List
- Reverse a singly Linked List in groups of given size | Set 3
- Reverse a doubly linked list in groups of given size
- Merge two sorted linked lists such that merged list is in reverse order
- Reverse a Linked List in groups of given size (Iterative Approach)
- Create new linked list from two given linked list with greater element at each node
- Merge a linked list into another linked list at alternate positions
- Convert singly linked list into circular linked list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. 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.