题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
import java.util.*; /* * public class ListNode { * int val; * ListNode next = null; * } */ public class Solution { /** * * @param head ListNode类 * @param k int整型 * @return ListNode类 */ public ListNode reverseKGroup (ListNode head, int k) { // write code here if(head == null || head.next == null || k < 2){ return head; } ListNode dummy = new ListNode(0); dummy.next = head; int len = 0; //统计链表中结点个数 ListNode prestart = dummy, start = head; while (head != null) { head = head.next; len++; } ListNode temp = null; //中间结点 放外面减少内存 for (int i = 0 ; i < len / k ; i++ ) { //进行分段 for (int j = 1 ; j < k ; j++ ) { //段内排序 temp = start.next; start.next = temp.next; temp.next = prestart.next; prestart.next = temp; } //此时start已经由第1位变为第三位 进入下一段 prestart = start; start = start.next; } return dummy.next; } }