LeetCode之Rotate List(Kotlin)

问题:



方法:
第一遍遍历先获得链表长度,然后通过取余去除无效的旋转次数,得到有效次数j。然后移动链表到倒数第j个点,把该点作为新的链表的头节点,然后把原来的头节点接到新链表的尾部即可。

package com.eric.leetcode

class RotateList {
    fun rotateRight(head: ListNode?, k: Int): ListNode? {
        var cur = head
        var count = 1
        while (cur?.next != null) {
            count++
            cur = cur.next
        }
        val end = cur
        cur = head
        val j = k % count
        for (index in 1 until (count - j)) {
            cur = cur?.next
        }
        end?.next = head
        val result = cur?.next
        cur?.next = null
        return result
    }
}

有问题随时沟通

具体代码实现可以参考Github

你可能感兴趣的:(LeetCode之Rotate List(Kotlin))