题解 | #链表中的节点每k个一组翻转#
链表中的节点每k个一组翻转
https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e
//1首先要明确翻转多少次 1 2 3 4 5 k=2 times=5/2=2
//2确立一个答案链表 ans
//3建立一个栈
//4每次放k个元素进栈
//5每次出k个元素进答案链表 把4,5进行times次
//把剩下的不足以k个的接在答案链表
import java.util.*;
public class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
int length = 0;
ListNode f = head;
while(f!=null){
length++;
f=f.next;
}
int times = length/k;
ListNode ans=new ListNode(-1);
ListNode now = head;
ListNode newone = ans;
Stack<ListNode> stack = new Stack<>();
for(int i = 0;i<times;i++) {
for (int j = 0; j < k; j++) {
stack.push(now);
now = now.next;
}
for (int g = 0; g < k; g++) {
newone.next = stack.pop();
newone = newone.next;
}
}
newone.next = now;
return ans.next;
}
}
