Today I solved geeksforgeeks problem https://practice.geeksforgeeks.org/problems/reverse-a-linked-list-in-groups-of-given-size/1 to reverse a linked in list in batch of K. The code I wrote was very different from the one suggested by their editorial solution so I am sharing the code here for everyone's benefit.
class Solution
{
public static Node reverse(Node node, int k)
{
Node head = null;
Node oldtail = null;
if(node==null) {
return null;
}
int i=1;
Node prev = node;
node = node.next;
Node newtail = prev;
prev.next = null;
while(node!=null) {
if(i%k==0) {
if(oldtail!=null) {
oldtail.next = prev;
} else {
head = prev;
}
oldtail = newtail;
prev = node;
newtail = prev;
node = node.next;
prev.next=null;
i++;
} else {
Node temp = node.next;
node.next = prev;
prev = node;
node = temp;
i++;
}
}
if(oldtail!=null) {
oldtail.next = prev;
}
if(head==null) {
head=prev;
}
return head;
}
}
No comments:
Post a Comment