LeetCode 25. Reverse Nodes in k-Group - Array

题目链接:25. Reverse Nodes in k-Group

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

Example:

Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

Note:

  • Only constant extra memory is allowed.
  • You may not alter the values in the list’s nodes, only nodes itself may be changed.

题解

力扣将此题设置为困难。不过我觉得这道题目并不难。

首先判断是否为空。
不为空的话,用数组保存不超过 k 个数,如果有 k 个数,就逆序赋值到这 k 个结点,不足 k 个数直接退出。
返回原头结点 head 即可。

时间复杂度 O ( 2 n ) O(2n) O(2n)
空间复杂度:一个一维数组, O ( k ) O(k) O(k)

Java代码

/**
 * 2020-1-31 18:37:14
 */
/**
 * 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) {
        if (head == null) {
            return null;
        }
        int[] arr = new int[k];// 保存k个数
        ListNode hk = head;// 每k个结点的头结点
        while (hk != null) {// 每一段的头结点是否存在
            ListNode p = hk;// 移动指针
            int len = 0;// 当前这一段有几个结点
            while (len < k && p != null) {// 找不超过k个结点直到为空
                arr[len] = p.val;// 保存结点的值
                ++len;// 个数加1
                p = p.next;// 向后移动指针
            }
            if (len < k) {
                break;// 不足k个结点,不用逆序,直接退出
            }
            for (int i = len - 1; i >= 0; --i) {// 有k个结点,逆序赋值
                hk.val = arr[i];
                hk = hk.next;
            }
        }
        return head;
    }
}

原文链接:https://blog.csdn.net/pfdvnah/article/details/104126675

- End - wowpH - pfdvnah -

你可能感兴趣的:(#,LeetCode,#,Java,Arrays)