@cxm-2016
2016-12-19T09:07:44.000000Z
字数 723
阅读 1782
算法
版本:2
作者:陈小默
声明:禁止商业,禁止转载
如题所属,删除一个链表中值重复出现的节点。
思路:在有限空间复杂度的情况下,我们可以采取遍历删除的方式。
data class Node(var value: Int, var next: Node?) {
override fun toString(): String {
val builder = StringBuilder().append('[')
var node: Node? = this.next
builder.append(value)
while (node != null) {
builder.append(',').append('\t').append(node.value)
node = node.next
}
return builder.append(']').toString()
}
}
fun delete(node: Node?) {
node ?: return
val delete = node.next
if (delete != null) {
node.next = delete.next
delete.next = null
} else node.next = null
}
fun deleteRepeated(head: Node) {
var index: Node? = head
var node: Node?
var value: Int
while (index != null) {
value = index.value
node = index
while (node != null) {
while (node.next != null && value == node.next!!.value) delete(node)
node = node.next
}
index = index.next
}
}