25. K 个一组翻转链表
之前嫌弃这个题目太无聊就不爱写,后来才知道是腾讯的面试题、、、
第20行
//反转
ListNode reverse = reverse(a, cur);
这部分的用法和之前AI托管里面放Map是一样的、、、所以后面用a.next=reverseKGroup(cur,k);,是没有逻辑问题存在的
其次就是这个递归的方法,用着也相对来说比较方便
/**
* 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) {
if(head==null) return null;
ListNode a=head,cur=head;
for (int i = 0; i < k; i++) {
if(cur==null) return head;
cur=cur.next;
}
//反转
ListNode reverse = reverse(a, cur);
//继续递归
a.next=reverseKGroup(cur,k);
return reverse;
}
public ListNode reverse(ListNode a, ListNode b){
ListNode head=null,cur=a;
while (cur!=b){
ListNode temp=cur.next;
cur.next=head;
head=cur;
cur=temp;
}
return head;
}
}