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

链表中的节点每k个一组翻转

https://www.nowcoder.com/practice/b49c3dc907814e9bbfa8437c251b028e

在BM2(https://www.nowcoder.com/discuss/536458489359622144?sourceSSR=users)的基础上借助node1和node2解决问题

import java.util.*;

/*
 * public class ListNode {
 *   int val;
 *   ListNode next = null;
 *   public ListNode(int val) {
 *     this.val = val;
 *   }
 * }
 */

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param head ListNode类
     * @param k int整型
     * @return ListNode类
     */
    public ListNode reverseKGroup (ListNode head, int k) {
        // write code here
        if (k == 1) {
            return head;
        }
        ListNode pointer = head;
        int length = 0;
        while (pointer != null) {
            pointer = pointer.next;
            length++;
        }
        int numOfGroup = length / k;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        int index = 1;
        ListNode node1 = dummy;
        ListNode node2 = dummy;
        ListNode prev = dummy;
        while (index <= k * numOfGroup) {
            int remain = index % k;
            ListNode next = head.next;
            if (remain == 1) {
                node2 = head;
            } else {
                head.next = prev;
            }
            if (remain == 0) {
                node1.next = head;
                node2.next = next;
                node1 = node2;
                node2 = next;
            }
            prev = head;
            head = next;
            index++;
        }
        return dummy.next;

    }
}

全部评论

相关推荐

MScoding:第一次见放闲鱼界面的
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务