For an assignment I am working on, we were instructed to create two data structures that implement a Stack inferface (including push, pop, etc.. methods). While I completed the first structure, the Linked List portion has me at a loss. As someone who is writing their first Go project, I am unsure how to approach the following instruction:
1.Create a new struct called StackLinked that implements Stacker, and uses a singly (or doubly) linked list as its internal representation.
2.In addition to implementing all the methods in Stacker, write a makeStackLinked() function (not method!) with this header that returns a new empty stack using a linked list representation
Which I had attempted to implement as so:
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;
}
I feel I may be over complicating things (I have only worked with Singly Linked Lists in C++).
Does anyone have any suggestions or recommendations on the best way to implement the StackLinked struct and accompanying initialization function?
EDIT: The function header: func makeStackLinked() StackLinked {} is a requirement for the assignment and cannot be altered.
Thank you!
Use the following:
type stackElement struct {
next *stackElement
data int
}
type StackLinked struct {
head *stackElement
n int
}
func makeStackLinked() Stacker {
return &StackLinked{}
}
You can use this following:
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