第一种解题思路:
- 循环链表,每次循环将链表的结点存进栈
- 判断栈的长度,是否等于 K ,等于 K,则循环出栈
- 循环链表后,判断栈是否为空,不为空则循环出栈
- 然后插入新链表的尾部
- 最后返回新链表
时间复杂度为O(n),空间复杂度为O(n),不合题意。
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if (head == null || head.next == null || k == 1) {
return head;
}
Stack<ListNode> stack = new Stack<>();
ListNode cur = new ListNode(-1);
ListNode pre = cur;
ListNode node = null;
while (head != null) {
stack.push(head);
head = head.next;
if (stack.size() == k) {
while (!stack.isEmpty()) {
node = stack.pop();
node.next = null;
cur.next = node;
cur = cur.next;
}
}
}
while (!stack.isEmpty()) {
node = stack.pop();
//一个个结点往cur后面插
node.next = cur.next;
cur.next = node;
}
return pre.next;
}
}
第二种方法:指针前移,分批往前移思想,参考牛客大佬"不上蓝到绿不改名"
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup (ListNode head, int k) {
// write code here
if (head == null || k <= 1) {
return head;
}
ListNode result = new ListNode(-1);
ListNode now = result;
int length = getLength(head);
//循环次数
int size = length / k;
for (int i = 0; i < size; i++) {
ListNode node = null;
ListNode tmp = null;
for (int j = 0; j < k; j++) {
node = head.next;
head.next = tmp;
tmp = head;
head = node;
}
now.next = tmp;
while (now.next != null) {
now = now.next;
}
}
now.next = head;
return result.next;
}
//计算链表的长度
private int getLength(ListNode head) {
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
}