go - 如何打印链表

标签 go linked-list

下面是代码:

package collection

type List struct {
    head *Node
    tail *Node
}

func (l *List) First() *Node {
    return l.head
}

func (l *List) Push(value int) {
    node := &Node{value: value}
    if l.head == nil { // list is empty
        l.head = node
    } else {
        l.tail.next = node
    }
    l.tail = node
}

func (l *List) String() string {
    var list string
    n := l.First()
    for n != nil {
        list = list + string(n.Value()) + " "
        n = n.Next()
    }
    return list
}

type Node struct {
    value int
    next  *Node
}

func (n *Node) Next() *Node {
    return n.next
}

func (n *Node) Value() int {
    return n.value
}

在调试时,元素成功推送

但是对于list = list + string(n.Value()) + " ",这是调试输出:list: " "
package main

import (
    "fmt"

    "github.com/myhub/cs61a/collection"
)

func main() {
    l := &collection.List{}
    l.Push(1)
    l.Push(2)
    l.Push(3)
    fmt.Println(l)
}

1)为什么list = list + string(n.Value()) + " "不连接整数?

2)如何为任何类型的成员Node支持value

最佳答案

使用strconv.Itoa()将int转换为字符串。

list = list + strconv.Itoa(n.Value()) + " "

在普通转换中,该值将解释为Unicode代码点,并且结果字符串将包含该代码点表示的字符,并以UTF-8编码。
s := string(97) // s == "a"

对于您的情况1,2,3都是不可打印的字符

关于go - 如何打印链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62241857/

相关文章:

timer - 如何从 Web 服务器重启(或代码刷新/升级)中恢复 Go 计时器?

json - 输入递归 golang 函数调用

c - 将字符添加到链接列表中

sorting - 在 Golang 中使用 map

http - 如何在 golang 中获取重定向 url 而不是页面内容?

在 C 中创建链表

java - 同时修改 HashMap 的条目是否安全...如果映射的大小是固定的并且条目是链表?

c - 这就是我在链表中​​创建链表的方式吗?

C中根据用户请求的元素个数创建链表

python - 如果所有字符串都需要一个长度或空终止符,那么高级语言如何只用字符构造一个字符串?