# Iterative Solution for Reverse Nodes in Groups of K Nodes

• The iterative solution is better as the recursive solution may use Stack memory and if you have a very large quantity of data like millions of node in LinkedList, your code may not provide the desired solution, give an error instead.

``````public ListNode reverseKGroup(ListNode head, int k) {
}
int l = 0;
//To find length of LL
while(temp!=null){
temp = temp.next;
l++;
}
if(k>l){
}
boolean flag = true;
ListNode p = null;
ListNode n = null;
ListNode tail1 = null;
ListNode tail2 = null;
while(c!=null){
int i=0;
if(flag){
tail1 = c;
}
else{
tail2 = tail1;
tail1 = c;
}
//remaining nodes are less than k
if(k>l){
if(tail2!=null){
tail2.next = tail1;
}
break;
}
p=null;
//reversing k nodes
while(i<k && c!=null){
//System.out.println("p");
n = c.next;
c.next = p;
p=c;
c = n;
i++;
}
l-=k;
if(flag){
flag=false;
}
else{
tail2.next = p;
}
}
}
``````

• ``````

``` private static ListNode ReverseKList(ListNode head, int k)
{

var setGroup = true;
ListNode firstNode = null;
ListNode secondTail = null;
ListNode firstTail = null;
ListNode prev = null;

if (head == null || head.Next == null || k == 1)
{
}

int length = 0;

//find length of list
while (temp != null)
{
temp = temp.Next;
length++;
}
if (k > length)
{
}

//reverse the list in k group
var group = k;
{

//reverse the list

if (setGroup)
{
// get the first group tail node address
// pre will have tail node intilally for each iteration of a group
if (firstTail == null)
firstTail = prev;

secondTail = prev;
setGroup = false;
}

if (--group == 0 || head == null)
{
if(firstNode==null)
firstNode = prev;

else
{
firstTail.Next = prev;
firstTail = secondTail;

}
prev = null;
group=k;
setGroup = true;
}

}
return firstNode;
}``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.