Skip to content

Instantly share code, notes, and snippets.

@sdsd08013
Last active October 14, 2020 19:11
Show Gist options
  • Select an option

  • Save sdsd08013/106c9bf173781a02c3081d23277c547d to your computer and use it in GitHub Desktop.

Select an option

Save sdsd08013/106c9bf173781a02c3081d23277c547d to your computer and use it in GitHub Desktop.
Kotlin Linked List
data class Node(
var name: String,
var next: Node?
)
fun printNode(node: Node) {
var tmp: Node? = node
while (tmp != null) {
print("${tmp.name}->")
tmp = tmp.next
}
print("\n")
}
fun main(args: Array<String>) {
var node = Node("A", Node("B", Node("C", Node("D", Node("E", null)))))
printNode(reverse(node, null))
}
fun reverse(node: Node, next: Node?): Node {
// 参照を渡せないので代入
var copyNode: Node? = node
var prev: Node? = null
while (copyNode != null) {
val tmp = copyNode.next
copyNode.next = prev
prev = copyNode
copyNode = tmp
}
return prev ?: node
}
fun recursiveReverse(node: Node, next: Node?): Node {
var last: Node? = null
if(node.next != null) {
val tmp = node.next!!
node.next = next
print("+=========")
recursiveReverse(tmp, node)
} else {
node.next = next
print("###############3#")
print("node")
print(node)
print(next)
last = node
}
print("***********")
print(node)
print(next)
return last ?: node
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment