描述
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 le�-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
分析
给定链表,一次反转链表k的节点并返回其修改的列表。
如果节点的数目不是k的倍数,那么最终的节点应该保持原样。
可能不会更改节点中的值,而只能更改节点本身。
例如,给定这个链表:1>2>3>4>5。
对于k=2,你应该返回:2 ->1 ->4>3>5。
对于k=3,你应该返回:3 ->2 ->1>4>5。
注意越界问题,
代码
1 public static ListNode reverseNodeInKGrop(ListNode head, int n) { 2 if (head == null || head.next == null || n == 1) 3 return head; 4 ListNode fakehead = new ListNode(-1); 5 fakehead.next = head; 6 ListNode ptr1 = head, ptr2 = fakehead.next.next, newstart = fakehead; 7 int len = 0; 8 while (ptr1 != null) { 9 len++; 10 ptr1 = ptr1.next; 11 } 12 ptr1 = fakehead.next; 13 if(n!=len) 14 n = n % len; 15 int k = len / n; 16 for (int j = 0; j < k; j++) { 17 18 for (int i = 1; i < n; i++) { 19 ptr1.next = ptr2.next; 20 ptr2.next = newstart.next; 21 newstart.next = ptr2; 22 ptr2 = ptr1.next; 23 } 24 25 for (int i = 0; i < n; i++) { 26 newstart = newstart.next; 27 } 28 29 if (ptr2 != null && ptr2.next != null) { 30 ptr1 = newstart.next; 31 ptr2 = ptr1.next; 32 } 33 } 34 35 return fakehead.next; 36 }