文章目录
1. 题目
2. 思路
(1) 伪头结点
- 新建伪头结点指向原链表的头结点,每次反转时,先用一个指针遍历链表,判断剩余结点是否有k个,若没有,则直接返回即可。
- 仔细修改结点间的指针即可。
3. 代码
public class Test {
public static void main(String[] args) {
}
}
class ListNode {
int val;
ListNode next = null;
}
class Solution {
/**
* @param head ListNode类
* @param k int整型
* @return ListNode类
*/
public ListNode reverseKGroup(ListNode head, int k) {
ListNode preHead = new ListNode();
preHead.next = head;
head = preHead;
while (true) {
ListNode next = head;
int n = k + 1;
while (next != null && n > 0) {
next = next.next;
n--;
}
if (n > 0) {
break;
}
ListNode node = head.next;
ListNode cur = node;
next = node;
n = k;
while (n > 0) {
node = node.next;
cur.next = head.next;
head.next = cur;
cur = node;
n--;
}
next.next = cur;
head = next;
}
return preHead.next;
}
}