Given the head
of a linked list, reverse the nodes of the list k
at a time, and return the modified list.
class Solution {标签:lastEnd,25,head,ListNode,next,return,Group,Nodes,stack From: https://www.cnblogs.com/MarkLeeBYR/p/16860665.html
public ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0);
dummy.next=head;
ListNode lastEnd=dummy;
Stack<ListNode> stack=new Stack<>();
while(head!=null){
ListNode first=head;
while(stack.size()<k&&head!=null){
stack.push(head);
head=head.next;
}
if(stack.size()<k) {
lastEnd.next=first;
break;
}
lastEnd.next=help(stack);
lastEnd=first;
}
return dummy.next;
}
ListNode help(Stack<ListNode> stack){
if(stack.size()==0) return null;
ListNode node = stack.pop();
node.next=help(stack);
return node;
}
}