题解 | #链表中的节点每k个一组翻转#

其实就是题目翻转链表的k个节点连续执行多次,每次都更换头结点。

import java.util.*;
public class Solution {
    public ListNode reverseKGroup (ListNode head, int k) {
        if (head == null || head.next == null || k == 1) return head;

        int len = 0;
        ListNode temp = head;
        while (temp != null) {
            temp = temp.next;
            len++;
        }
        
        ListNode newHead = new ListNode(0);
        newHead.next = head;
        ListNode pre = newHead;
        for (int j = k ; j <= len; j += k) {            
            ListNode cur = newHead.next;
            for (int i = 1; i <= k; i++) {
                ListNode curNext = cur.next;
                cur.next = newHead.next;
                newHead.next = cur;
                cur = curNext;
            }
            head.next = cur;
            
            newHead = head;
            head = cur;
        }
        return pre.next;
    }
}
全部评论

相关推荐

05-26 10:24
门头沟学院 Java
qq乃乃好喝到咩噗茶:其实是对的,线上面试容易被人当野怪刷了
点赞 评论 收藏
分享
昨天 15:52
东南大学 C++
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务