题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*;
public class Solution {
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if (head == null)
return head;
ListNode head1 = head;
//记录链表总长度
int length = 1;
while(head1.next!=null){
head1 = head1.next;
length++;
}
// System.out.print("length="+length);
head1 = head;
int arr [] = new int [length];
int i =0;
//将链表中的值放入数组中
while(i<length){
arr[i++] = head1.val;
head1 = head1.next;
}
head1 = head;
// System.out.print("first:");
// for(int j :arr){
// System.out.print(j);
// }
//count指的是反转count次
int count = length/k;
//count1指的是每次反转调换count次
int count1=k/2;
// System.out.println("count = "+count+"count1="+count1);
for(int n = 0;n<count;n++){
// 反转count次,每次循环,反转的部分总长度为n*k-n*k+k,基础长度为n*k
//所以调换的元素为n*k和n*k+k,在m1的大小中调换
for(int m1 =0;m1<count1;m1++){
int temp = arr[n*k+m1];
arr[n*k+m1] = arr[n*k+k-m1-1];
arr[n*k+k-m1-1] = temp;
}
}
// System.out.print("secound:");
for(int j :arr){
// System.out.print(j);
head1.val = j;
head1 = head1.next;
}
return head;
}
}
