题解 | #链表中的节点每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;
    }
}
全部评论

相关推荐

11-11 14:21
西京学院 C++
Java抽象练习生:教育背景放最前面,不要耍小聪明
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务