题解 | #K个一反转#
链表中的节点每k个一组翻转
http://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) { int count = 0; ListNode cur = head; while (cur != null) { count++; cur = cur.next; } if (count < k) { return head; } int term = count / k; ListNode preHead = new ListNode(-1); preHead.next = head; ListNode pre = preHead; ListNode tail; ListNode next; for (int i = 0; i < term; i++) { tail = pre.next; for (int j = 0; j < k - 1; j++) { next = tail.next; tail.next = next.next; next.next = pre.next; pre.next = next; } pre = tail; } return preHead.next; } }