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:
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
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode reverseKGroup(ListNode head, int k) { if(null == head) return null; ListNode[] lArr = new ListNode[k]; ListNode resPreHead = new ListNode(0); ListNode resIndex = resPreHead; ListNode preHead = new ListNode(0); preHead.next = head; // index pointer indexP ListNode indexP = new ListNode(0); indexP.next = preHead.next; while(null != indexP.next){ ListNode kIndex = indexP; for(int i = 0; i < k; ++i){ if(null == kIndex.next){ resIndex.next = indexP.next; return resPreHead.next; }else{ lArr[i] = kIndex.next; kIndex = kIndex.next; } } // assign indexP to next back indexP.next = kIndex.next; for(int i = k-1; i >=0; --i){ resIndex.next = lArr[i]; resIndex = resIndex.next; if(i == 0){ resIndex.next = null; }else{ resIndex.next = lArr[i-1]; } } } return resPreHead.next; } }
No comments:
Post a Comment