/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
Deque<ListNode> stack = new ArrayDeque<ListNode>();
ListNode dummy = new ListNode(0);
ListNode p = dummy;
while (true) {
int count = 0;
ListNode tmp = head;
while (tmp != null && count < k) {
stack.add(tmp);
tmp = tmp.next;
count++;
}
if (count != k) {
p.next = head;
break;
}
while (!stack.isEmpty()){
p.next = stack.pollLast();
p = p.next;
}
p.next = tmp;
head = tmp;
}
return dummy.next;
}
}
用栈的方法,空间复杂度应该是O(k),而不是常数的额外空间