25. reverse nodes in k Group

o— layout : post title : “25. Reverse Nodes in k-Group” category : algorithm[LeetCode] tags: [LeetCode] —

  • Source : Link
  • Author : Han
  • Date : 2022-02-23

Problems

Given the head of a linked list, reverse the nodes of the list k at a time, and return the 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.

You may not alter the values in the list’s nodes, only nodes themselves may be changed.

Example 1:

https://assets.leetcode.com/uploads/2020/10/03/reverse_ex1.jpg

1
2
3
Input: head = [1,2,3,4,5], k = 2
Output: [2,1,4,3,5]

Example 2:

https://assets.leetcode.com/uploads/2020/10/03/reverse_ex2.jpg

1
2
3
Input: head = [1,2,3,4,5], k = 3
Output: [3,2,1,4,5]

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/**
 * Example:
 * var li = ListNode(5)
 * var v = li.`val`
 * Definition for singly-linked list.
 * class ListNode(var `val`: Int) {
 *     var next: ListNode? = null
 * }
 */
class Solution {
    fun reverseKGroup(head: ListNode?, k: Int): ListNode? {
        var curr = head
        var result = head
        var count = 0
        while (curr != null && count != k) {
            curr = curr.next
            count++
        }

        if (count == k) {
            curr = reverseKGroup(curr, k)
            while (count-- > 0) {
                val temp = result?.next
                result?.next = curr
                curr = result
                result = temp
            }
            result = curr
        }
        return result
    }
}