力扣 链表三

25. K 个一组翻转链表

labuladong 题解思路

之前嫌弃这个题目太无聊就不爱写,后来才知道是腾讯的面试题、、、
第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;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 400-110=290动态规划,还有栈 搞定之后,大约是130还有270道、、一天两道外加上复盘、、 JVM、 ...
    李笑笑9804阅读 63评论 0 0
  • to-do:看一下别人写的题解 https://github.com/981377660LMT/algorithm...
    winter_sweetie阅读 775评论 1 0
  • 64. 最小路径和[https://leetcode.cn/problems/minimum-path-sum/]...
    李笑笑9804阅读 69评论 0 0
  • 读完本文,你可以去力扣拿下如下题目: 25.K个一组翻转链表[https://leetcode-cn.com/pr...
    labuladong阅读 537评论 0 3
  • 题目汇总 🍃1、移除元素 203. 移除链表元素[https://leetcode-cn.com/problems...
    FlowerDancee阅读 235评论 0 0