leetcode25_k个节点一组翻转链表
public static ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next = head;
ListNode current = dummy;
while (current != null && current.next != null) {
ListNode mostleft = current.next;
ListNode mostright = mostleft;
// 获取最右端节点
int i;
for (i = k - 1; i > 0; i--) {
if (mostright.next == null) {
break;
}
mostright = mostright.next;
}
// 剩下的节点不够反转
if (i > 0)
break;
ListNode next = mostright.next;
// mostleft到mostright的反转
ListNode innerPre = null;
ListNode innerCur = mostleft;
while (innerCur != next) {
ListNode innerNext = innerCur.next;
innerCur.next = innerPre;
innerPre = innerCur;
innerCur = innerNext;
}
current.next = mostright;
mostleft.next = next;
current = mostleft;
}
return dummy.next;
}