# Simple Java Solution O(n)

• Reversing K elements at a time and moving forward

Steps
1.We have created a method reverseSubList which reverse the sublist and return new head.
2.Our main method calls reverseSubList each time with new head moving K time forward and join returned new headwith previously saved tail .
3.We keep doing this in loop and each time subtracting K from the original length .
4.Logic will keep running till the time we have enough element remaining in the list i.e. > K

``````/**
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
class Solution {

/**
*
* @param k reverse the nodes of a linked list k at a time
*/
public  ListNode reverseKGroup(ListNode head, int k) {

ListNode tailOfLastReversedSubList = null;
while (currentSubListHead != null && length >= k && k > 1) {

int i = 1;

//Below while will save the head for next sublist to get reversed;
while (headNodeForNextSubList != null && i <= k) {
i++;
}
}
if (tailOfLastReversedSubList == null) {
} else {
}

}
length =length-k;
}

//Below if will add the remaining elements(whose count is less than K) to last reversed sub list tail
if (tailOfLastReversedSubList != null) {
}

}

/**
* @param k
*            integer determining sublist
* @return new head of reversed sublist
*/
private  ListNode reverseSubList(ListNode sublistHead, int k) {
int counter = 0;
ListNode resumeNode = null;
ListNode previous = null;
while (counter < k - 1 && sublistHead != null && sublistHead.next != null) {
// Reversing pointer for two consecutive node
resumeNode = temp.next;

previous = temp;
counter = counter + 2;
}

//this condition will take care of last node if K is odd number
if (sublistHead != null && counter == (k - 1)) {

}
return previous;

}

/**
* @param node
*            to calculate the length
* @return length of the list from the node
*/
private  int lengthFromNode(ListNode node) {
ListNode temp = node;
int result = 0;
while (temp != null) {
result++;
temp = temp.next;
}
return result;
}
}
``````

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