Files
hello-algo/ja/codes/kotlin/utils/PrintUtil.kt
Yudong Jin 7257641e0e Retranslate the complete Japanese online edition from Chinese (#2008)
* Retranslate the complete Japanese online edition from Chinese

* Fit Japanese homepage labels and localize heading permalinks

* Point Japanese contribution instructions to the Japanese preview

* Replace locale conditionals with multilingual UI tables
2026-10-30 02:12:26 +08:00

107 lines
2.3 KiB
Kotlin
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* File: PrintUtil.kt
* Created Time: 2024-01-25
* Author: curtishd (1023632660@qq.com)
*/
package utils
import java.util.*
class Trunk(var prev: Trunk?, var str: String)
/* 行列を表示する(Array) */
fun <T> printMatrix(matrix: Array<Array<T>>) {
println("[")
for (row in matrix) {
println(" $row,")
}
println("]")
}
/* 行列を表示する(List) */
fun <T> printMatrix(matrix: MutableList<MutableList<T>>) {
println("[")
for (row in matrix) {
println(" $row,")
}
println("]")
}
/* 連結リストを表示する */
fun printLinkedList(h: ListNode?) {
var head = h
val list = mutableListOf<String>()
while (head != null) {
list.add(head._val.toString())
head = head.next
}
println(list.joinToString(separator = " -> "))
}
/* 二分木を表示する */
fun printTree(root: TreeNode?) {
printTree(root, null, false)
}
/**
* 二分木を表示する
* この木の表示処理は TECHIE DELIGHT から借用した
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
fun printTree(root: TreeNode?, prev: Trunk?, isRight: Boolean) {
if (root == null) {
return
}
var prevStr = " "
val trunk = Trunk(prev, prevStr)
printTree(root.right, trunk, true)
if (prev == null) {
trunk.str = "———"
} else if (isRight) {
trunk.str = "/———"
prevStr = " |"
} else {
trunk.str = "\\———"
prev.str = prevStr
}
showTrunks(trunk)
println(" ${root._val}")
if (prev != null) {
prev.str = prevStr
}
trunk.str = " |"
printTree(root.left, trunk, false)
}
fun showTrunks(p: Trunk?) {
if (p == null) {
return
}
showTrunks(p.prev)
print(p.str)
}
/* ハッシュテーブルを表示する */
fun <K, V> printHashMap(map: Map<K, V>) {
for ((key, value) in map) {
println("${key.toString()} -> $value")
}
}
/* ヒープを表示する */
fun printHeap(queue: Queue<Int>?) {
val list = mutableListOf<Int?>()
queue?.let { list.addAll(it) }
print("ヒープの配列表現:")
println(list)
println("ヒープの木構造表現:")
val root = TreeNode.listToTree(list)
printTree(root)
}