問題:
方法:
第一遍遍歷先獲得鏈表長度,然后通過取余去除無效的旋轉(zhuǎn)次數(shù),得到有效次數(shù)j。然后移動鏈表到倒數(shù)第j個點,把該點作為新的鏈表的頭節(jié)點,然后把原來的頭節(jié)點接到新鏈表的尾部即可。
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
}
}
有問題隨時溝通
