题目
旋转链表
问题:
给定一个链表,旋转链表,将链表每个节点向右移动k个位置,其中k是非负数。
示例:
输入:1->2->3->4->5->null 和 k=2
输出:4->5->1->2->3->null
代码:
/**
public class SingNode {
public var value : Int
public var nextNode: SingNode?
public init(value:Int) {
self.value = value
}
}
extension SingNode : CustomStringConvertible {
public var description: String {
var string = "\(value)"
var node = self.nextNode
while node != nil {
string = string + " -- " + "\(node!.value)"
node = node?.nextNode
}
return string
}
}
**/
func rotateRightNode(_ l1:SingNode?, _ right:Int) -> SingNode? {
if l1 == nil {
return nil
}
var total = 0
var p = l1
var last = p
while p != nil {
total += 1
last = p
p = p?.nextNode
}
let rightIndex = right%total
if rightIndex == 0 {
return l1
}
let dummyNode = SingNode.init(value: 0)
dummyNode.nextNode = l1
p = dummyNode
for _ in 0..<rightIndex {
p = p?.nextNode
}
let ret = p?.nextNode
p?.nextNode = nil
last?.nextNode = dummyNode.nextNode
return ret
}