Wednesday, September 6th
Linked list splitting.
Given the head of a linked list, and an integer k, divide the linked list into k consecutive linked lists
A line splitting into parts, courtesy of David Shankbone via Wikipedia. Licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license. No changes made.The idea is to first compute the length of the array, so then, using k, we can determine the length of a divided line, plus any remainder.
First, initiate the answer vector and test for an empty list
Then get the length of the list, and compute the size and remainder
Then we iterate for each answer in the answer segments k. We will keep track of the current element, and the previous element, because at the end of each segment we need to change the end of the segment to null. At the start of the loop we will set the answer array entry to the head of the list
Because each division of the list contains s element, iterate through the list s times
To compensate for any imbalances in the division, check the remainder r, and if there is any left, iterate an extra element while testing for an empty node. Reduce the remainder by 1.
Finally, for the reason we have been tracking previous elements in addition to the current node, change the end of the list division so that the last node points to null
Return the answer array
Thanks to shubham_kr23 for clearly demonstrating how to incorporate the remainder
Comments
Post a Comment