61. Rotate List

复制代码
package LeetCode_61

/**
 * 61. Rotate List
 * * https://leetcode.com/problems/rotate-list/
 *
 * Given a linked list, rotate the list to the right by k places, where k is non-negative.
 *
Example 1:
Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:
Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
 * */
class ListNode(var `val`: Int) {
    var next: ListNode? = null
}

class Solution {
    /*
    * solution, step:
    * 1. count the length of ListNode and find out tail
    * 2. find out new-head's prev node and set this prev node.next = null
    * 3. set tail.next = head
    * Time complexity:O(n), Space complexity:O(1)
    * */
    fun rotateRight(head: ListNode?, k: Int): ListNode? {
        if (head == null) {
            return null
        }
        //if not null, mean length at least 1
        var length = 1
        var tail = head
        //avoid set tail to null
        while (tail!!.next != null) {
            length++
            tail = tail.next
        }
        //rotate k time == rotate k % length time, avoid k larger than length
        val k_ = k % length
        if (k_ == 0) {
            //after k step, the same with the old head
            return head
        }
        /*
        * find out newHead's prev node, for example: 1->2->3->4->5, k=2, need change into: 4->5->1->2->3
        * newHead should be 4,it's prev node is 3, and 3 is the tail of newHead, so set 3.next = null
        * */
        var prevOfNewHead = head
        for (i in 0 until length - k_ - 1) {
            prevOfNewHead = prevOfNewHead!!.next
        }
        //create new head
        val newHead = prevOfNewHead!!.next
        prevOfNewHead.next = null
        //set 5.next = old head
        tail!!.next = head
        return newHead
    }
}
复制代码

 

posted @   johnny_zhao  阅读(89)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
历史上的今天:
2019-10-30 53. Maximum Subarray
点击右上角即可分享
微信分享提示