Go 用一个结构初始化单链表
对于我正在处理的任务,我们被指示创建两个实现堆栈推断面的数据结构(包括push、pop等方法)。当我完成第一个结构时,链表部分让我不知所措。作为编写第一个Go项目的人,我不确定如何进行以下说明: 1.创建一个名为StackLinked的新结构,该结构实现Stacker,并使用单(或双)链接列表作为其内部表示形式 2.除了实现Stacker中的所有方法外,还可以使用此标头编写一个makeStackLinked()函数(不是方法!),该函数使用链表表示返回一个新的空堆栈 我曾试图实现以下目标:Go 用一个结构初始化单链表,go,struct,initialization,singly-linked-list,Go,Struct,Initialization,Singly Linked List,对于我正在处理的任务,我们被指示创建两个实现堆栈推断面的数据结构(包括push、pop等方法)。当我完成第一个结构时,链表部分让我不知所措。作为编写第一个Go项目的人,我不确定如何进行以下说明: 1.创建一个名为StackLinked的新结构,该结构实现Stacker,并使用单(或双)链接列表作为其内部表示形式 2.除了实现Stacker中的所有方法外,还可以使用此标头编写一个makeStackLinked()函数(不是方法!),该函数使用链表表示返回一个新的空堆栈 我曾试图实现以下目标: ty
type StackLinked struct{
top *StackLinked
next *StackLinked
data int
size int
}
func makeStackLinked() Stacker {
list := &StackLinked{
top : nil,
next : nil,
data : 0,
size : 0,
}
return list;
}
我觉得事情可能过于复杂了(我只在C++中使用过单链表)
是否有人对实现StackLinked结构及其附带的初始化功能的最佳方法有任何建议或建议
编辑:函数头:func makeStackLinked()StackLinked{}是赋值的必要条件,不能更改
谢谢大家! 使用以下命令:
type stackElement struct {
next *stackElement
data int
}
type StackLinked struct {
head *stackElement
n int
}
func makeStackLinked() Stacker {
return &StackLinked{}
}
type Student struct {
Name string `json:"name"`
ID string `json:"id"`
Next *Student
}
func (s *Student) Insert(name, sid string) {
st := &Student {
Name: name,
ID: sid,
Next: s.Next,
}
s.Next = st
}
func (s *Student) Show() {
for st := s.Next; st != nil; st = st.Next {
fmt.Println(st.Name,st.ID)
}
}
func main ( ) {
root := new ( Student )
root.Insert ( "Juan", "54542" )
root.Insert ( "Lito", "93828" )
root.Show()
}
Output:
Lito 93828
Juan 54542
您可以使用以下方法:
type stackElement struct {
next *stackElement
data int
}
type StackLinked struct {
head *stackElement
n int
}
func makeStackLinked() Stacker {
return &StackLinked{}
}
type Student struct {
Name string `json:"name"`
ID string `json:"id"`
Next *Student
}
func (s *Student) Insert(name, sid string) {
st := &Student {
Name: name,
ID: sid,
Next: s.Next,
}
s.Next = st
}
func (s *Student) Show() {
for st := s.Next; st != nil; st = st.Next {
fmt.Println(st.Name,st.ID)
}
}
func main ( ) {
root := new ( Student )
root.Insert ( "Juan", "54542" )
root.Insert ( "Lito", "93828" )
root.Show()
}
Output:
Lito 93828
Juan 54542
为什么,错误是显而易见的。只需将返回类型更改为
*StackLinked
或删除&
。对于en empty struct,只需StackLinked{}
就足够了。感谢您的回复。我已经摆脱了&,那是一个愚蠢的错误。主要的问题是过于复杂。@我认为所需的签名是func makeStackLinked()Stacker
,其中Stacker
是您的作业中指定的接口。@CeriseLimón这是正确的!谢谢你指出这一点。在这种情况下,你需要返回&StackLinked{}
谢谢你的帮助!我相信现在一切都好了。仍然与我最初的实现类似,但它很有效,所以我不能抱怨。