小编Kha*_*sam的帖子

在 Kotlin 中实现链表

我最近开始学习 Kotlin,所以我决定在其中实现一些数据结构。所以,我尝试实现一个单链表:

package datastructures

public class LinkedList {
    private data class Node(var nodeValue: Int, var next: Node? = null)
    private var head: Node? = null

    fun insert(n: Int) {
        if(head == null) head = Node(n)
        else {
            var cur = head
            while(cur?.next != null) {
                cur = cur?.next
            }
            cur?.next = Node(n)
        }
    }

    fun print() {
        var cur = head
        while(cur != null) {
            print("${cur.nodeValue} ")
            cur = cur?.next
        }
    }

}

fun main(args: Array<String>) {
    val n = …
Run Code Online (Sandbox Code Playgroud)

linked-list kotlin

6
推荐指数
1
解决办法
5472
查看次数

标签 统计

kotlin ×1

linked-list ×1