1、题目
image.png2、分析
方法一:就按照第92题,反转链表的题目来写就好了。每次传的left和right的参数 + k就好了
方法二:递归法:
https://labuladong.github.io/zgnb/2/4/
3、代码
方法一的代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode listHead = head;
ListNode cur = head;
int j = 1;
while(cur != null){
//查看是否已经到链表尾部
int i = 0;
for(i = 0; i < k; i++){
if(cur == null) break;
cur = cur.next;
}
if(cur == null && i != k) break; //到达链表尾部,i = k的情况,是刚好整数的情况
//按照区间,反转链表
if(listHead == head){
listHead = reverseList(listHead, j, j + k - 1);
}
else{
reverseList(listHead, j, j + k - 1);
}
j = j + k;
}
return listHead;
}
private ListNode reverseList(ListNode head, int left, int right){
ListNode dummyNode = new ListNode(-1);
dummyNode.next = head;
ListNode pre = dummyNode;
ListNode cur = dummyNode.next;
for(int i = 0; i < left - 1; i++){
pre = pre.next;
cur = cur.next;
}
for(int i = 0; i < right - left; i++){
ListNode removeNode = cur.next;
cur.next = removeNode.next;
removeNode.next = pre.next;
pre.next = removeNode;
}
return dummyNode.next;
}
}
网友评论