25. 【困难】K 个一组翻转链表

25. K 个一组翻转链表


链接

题目描述

在这里插入图片描述

思路

在这里插入图片描述
在这里插入图片描述

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode pre = dummy;
        ListNode end = dummy;
        
        while(end.next != null){
            for(int i = 0; i < k && end != null; i++){
                end = end.next;
            }
            if(end == null){
                break;
            }
            ListNode start = pre.next;
            ListNode next = end.next;
            end.next = null;//为了方便reverse函数
            pre.next = reverse(start);
            start.next = next;
            pre = start;
            end = start;
        }
        return dummy.next;
    }
    
    //反转链表
    private ListNode reverse(ListNode start){
        ListNode pre = null;
        ListNode cur = start;
        
        while(cur != null){
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}
发布了55 篇原创文章 · 获赞 1 · 访问量 875

猜你喜欢

转载自blog.csdn.net/weixin_42469108/article/details/103744288
今日推荐