Go 如何打印链表
代码如下:Go 如何打印链表,go,linked-list,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.h
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:“
1) 为什么
list=list+string(n.Value())+“
不包含整数
2) 如何为任何类型的成员值支持节点?使用strconv.Itoa()
将int转换为字符串
list = list + strconv.Itoa(n.Value()) + " "
在普通转换中,该值被解释为Unicode代码点,结果字符串将包含该代码点表示的字符,以UTF-8编码
s := string(97) // s == "a"
对于您的案例1、2、3都是不可打印的字符1),为了将int转换为字符串,您需要使用。有一个。2) 这在Go中比较困难,因为它没有泛型,所以您需要使用接口{}
(空接口)使其工作。您还需要进行许多类型断言。更好的方法是使用普通切片,因为它们可以支持许多类型的类型safetyTrystrconv.Itoa(n.Value())
instead@xarantolus为什么string(n.Value())
不能进行类型转换时没有给出编译时错误?它确实进行了类型转换,它们只是字符值1,2,还有3个是不可打印的字符。@Marc找到你了。。。ascii值(或UTF-8值可能为)为1的字符为不可打印字符,是吗
s := string(97) // s == "a"