From LeetCode No.25;
Tier:Hard
Content:
Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
Example:
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5
A Solution With Java:
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
int n=k;
ListNode p=head,end=null;
while(p!=null&&n!=0){
end=p;
p=p.next;
n--;
}
if(n!=0)return head;
end.next=reverseKGroup(end.next, k);
while(head!=end){
p=head;
head=head.next;
p.next=end.next;
end.next=p;
}
return end;
}
}