题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
function reverseKGroup( head , k ) {
// write code here
let arr = [];
let temp = []
let p = head;
while(p){
arr.push(p.val);
p = p.next;
}
if(arr.length<k){
return head
}
let startIndex = 0;
let endIndex = 0;
for(let i= 0; i<arr.length;i++){
startIndex = i
if((startIndex+1) % k === 0){
temp.push(arr.slice(endIndex,startIndex+1).reverse())
endIndex = startIndex+1;
}
}
temp = temp.flat();
if(temp.length<arr.length){
while(arr.length-temp.length !== 0){
temp.push(arr[temp.length])
}
}
p = head;
while(p){
p.val = temp.shift()
p= p.next
}
return head
}
module.exports = {
reverseKGroup : reverseKGroup
};
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
function reverseKGroup( head , k ) {
// write code here
let arr = [];
let temp = []
let p = head;
while(p){
arr.push(p.val);
p = p.next;
}
if(arr.length<k){
return head
}
let startIndex = 0;
let endIndex = 0;
for(let i= 0; i<arr.length;i++){
startIndex = i
if((startIndex+1) % k === 0){
temp.push(arr.slice(endIndex,startIndex+1).reverse())
endIndex = startIndex+1;
}
}
temp = temp.flat();
if(temp.length<arr.length){
while(arr.length-temp.length !== 0){
temp.push(arr[temp.length])
}
}
p = head;
while(p){
p.val = temp.shift()
p= p.next
}
return head
}
module.exports = {
reverseKGroup : reverseKGroup
};