美文网首页
LeetCode 61. Rotate List

LeetCode 61. Rotate List

作者: phantom34 | 来源:发表于2019-06-04 15:59 被阅读0次

题目

61. Rotate List

描述

给出一个链表然后向右移动k位(k非负)

样例

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
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

题解

看过样例都知道k次右移中列表可能会恢复原来的次序好几次 所以我们先得到链表的长度length 然后k对length取余求出实际位移的次数
然后对链表进行位移操作最后输出 新的链表就好了

代码

    var list = mutableListOf<Int>()
    var next = head
    var result = ListNode(0)
    var now = result
    if (k == 0)
        return head
    while (next != null) {
        list.add(next.`val`)
        next = next.next
    }
    if (list.size == 0)
        return head
    var count = k % list.size
    for (i in list.size - count..list.size * 2 - count) {

    }
    var i = list.size - count
    while (i in list.size - count until list.size * 2 - count) {
        now.next = ListNode(list[i % list.size])
        now = now.next!!
        i++
    }

    return result.next
}

提交结果

image.png

相关文章

网友评论

      本文标题:LeetCode 61. Rotate List

      本文链接:https://www.haomeiwen.com/subject/ajfrxctx.html