leetcode - reverse nodes in K groups
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.
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
这道题目我们可以和reverse linkedlist ii 联系在一起。 我们把这个题目分为两部分:
1. 求出linkedlist的长度然后遍历整个linkedlist 按照区间为k, 把整个linekedlist变成 floor(length / k)
2.对于每一段,我们可有起始index和终点index,然后把这段之间的nodes reverse
这样我们就完成了这个题目。 这个题目的最困难的地方我觉得是 reverse,可能是reverse linkedlist的时候我忘记之前是怎么做的了, 花了好几天 TT.
1 class Solution { 2 3 public ListNode reverseKGroup(ListNode head, int k) { 4 if (k == 0 || k == 1 || head == null) { 5 return head; 6 } 7 int length = 0; 8 ListNode current = head; 9 while (current != null) { 10 current = current.next; 11 length++; 12 } 13 ListNode dummy = new ListNode(1); 14 dummy.next = head; 15 ListNode start = dummy; 16 for (int i = 0; i <= length - k; i = i + k) { 17 start = reverseList(start, i, i + k - 1); 18 } 19 return dummy.next; 20 } 22 ListNode reverseList(ListNode root, int start, int end) { 23 int count = start; 24 ListNode current = root.next.next; 25 ListNode pre = root.next; 26 ListNode endNode = pre; 27 while (count < end) { 28 ListNode following = current.next;30 current.next = pre; 31 pre = current; 32 current = following; 33 count++; 34 } 35 root.next = pre; 36 endNode.next = current; 37 return endNode; 38 } 39 }