题目描述
Java解决方法
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode l = new ListNode(0);
l.next = head;
ListNode pre = l;
ListNode end = l;
while (end.next != null)
{
for (int i = 0; i < k && end != null; i++)
{
end = end.next;
}
if (end == null)
{
break;
}
ListNode start = pre.next;
ListNode next = end.next;
end.next = null;
pre.next = reverse(start);
start.next = next;
pre = start;
end = pre;
}
return l.next;
}
private ListNode reverse(ListNode head) {
ListNode pre = null;
ListNode curr = head;
while (curr != null)
{
ListNode next = curr.next;
curr.next = pre;
pre = curr;
curr = next;
}
return pre;
}
}