Monday, January 25, 2016

Reverse K nodes in Java



Example:
Inputs:  1->2->3->4->5->6->7->8->NULL and k = 3 
Output:  3->2->1->6->5->4->8->7->NULL. 

Inputs:   1->2->3->4->5->6->7->8->NULL and k = 5
Output:  5->4->3->2->1->8->7->6->NULL. 



public ListNode reverseKnodes(ListNode head, int k) {
ListNode current = head;
ListNode prevTail = null;
ListNode prevCurrent = head;
while (current != null) {
int count = k;
ListNode tail = null;
while (current != null && count > 0) {
ListNode next = current.getNext();
current.setNext(tail);
tail = current;
current = next;
count--;
}
if (prevTail != null) {
prevTail.setNext(tail);
} else {
head = tail;
}
prevTail = prevCurrent;
prevCurrent = current;
}
return head;

}

No comments:

Post a Comment