题目:
Reverse Nodes in k-Group
在组内作反转
Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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 list’s nodes, only nodes themselves may be changed.
Example 1:
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]
//思路:递归思想:
//先把它成k段,每一段k段里面做反转操作,
//(先递归,直接到最后一段,递归是分段找的是每一段的最后一个节点)
var reverseKGroup = function(head, k) {
let count=0;
current=head;//每一段的开头
while(current!==null && count!==k){
current=current.next;
count++;
} //最后的current是下一段的起点
if(count==k){ //现在得到当前段的开头head 和 下一段的开头 current,做反转操作
current = reverseKGroup(current, k);
while(count>0){
let next=head.next;
head.next=current;
current=head;
head=next;
count--;
}
head=current; //以为head一直移动到最后的null
}
return head;//如果不够k,则直接返回 !!注意head是不动的,一直动的是current
}
//总结:一段链表 反转接到另一段链表的 ,即找每一段链表的开头节点,然后做反转