Reverse a Linked List in Groups of Given Size
This problem was a POTD of GFG for the month of July, I think this was yesterday's potd, which I had finished just minutes before the midnight on the clock. The practicals are finished today although there wasn't much that I gave for them out of my daily time but still they take a lot of daytime. I have finished almost everything for today, if I don't count the lecture so what about a blog?
I thought that this problem was quite interesting in terms of the simplicity it shows but the complexity it possesses, I feel that this was fairly a long time, since I handled or did something related to Linked Lists, and the problem also took much more time than I would expect, because of that reason I guess.
This problem basically examined or visualisation, or maybe your memory if you had done something like this before.
Overall, I felt that the banal idea of having to store the first number of every group and then when we get to the end number of the next group, say y, then making that number(or node whatever) point to y would do the needful, making sure that we are continuously making the elems point to the elem previous to it, because that's what we wanna do, reverse the elems of a group.
After all this mess, the last problem was making sure that we handle the condition where the group may not be complete, means there can be a group of size 5 which has just 2 elems.
Last but not the least and the most time consuming part was to make the overall last elem of the result linked list point to None, so that there would be some ending to the linked list and the list won't just point to 2 elems, back and forth making the linked list and infinite one.
So, I feel that this would be really interesting for someone who atleast have some logical thinking base for a linked list traversal or the basic operations of an ll, like removing some elems at some positions or like that.
The code has comments that are hopefully informative enough, the interesting part to look forward to is that there are 2 prevGroupElems, that is, 1 and 2, bcz if you would think about it, then you would notice that we'll have to store the first elem of the next group also before we can reach the end of that group,
for ex.: 1,2,3, 4,5,6 , 7,8,9
with k=3, means here we have these 3 groups.
so will store 1 in prevGroupElem1 and then before I can get to 6, will also have to store 4 for later use, so that I don't have to come back for it, so that would be temporarily in the prevGroupElem2, and after getting to 6 will make 1 point to 6 and will put 4 in prevGroupElem1, making the prevGroupElem2 empty for the storage of next group's 1st element(that is 7).
I think that's it for this one.
Cya ;)
Code:-
Comments
Post a Comment