Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For
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
1 public class Solution { 2 public ListNode reverseKGroup(ListNode head, int k) { 3 if(head==null || k==1) return head; 4 ListNode safe = new ListNode (-1); safe.next = head; 5 ListNode pre = safe, cur = head, post = head.next, p=head; 6 int len = 0; 7 8 while(p!=null){ 9 p=p.next; 10 len++; 11 } 12 int times = len/k; 13 for(int i=0;i<times;i++){ 14 post = cur.next; 15 int j=0; 16 while(post!=null){ 17 ListNode temp = post.next; 18 post.next = cur; 19 cur = post; 20 post = temp; 21 j++; 22 if(j==k-1) break; 23 } 24 ListNode temp = pre.next; 25 pre.next = cur; 26 temp.next = post; 27 pre = temp; 28 cur = post; 29 } 30 return safe.next; 31 } 32 }