Solution Review: Implement Stack Data Structure
This lesson discusses the solution to the challenge given in the previous lesson.
package mainimport ("fmt""strconv")const LIMIT = 4 // DONOT CHANGE IT!type Stack struct {ix int // first free position, so data[ix] == 0data [LIMIT]int}func (st *Stack) Push(n int) {if st.ix == LIMIT {return // stack is full!}st.data[st.ix] = nst.ix++ // increment total no. of elements present}func (st *Stack) Pop() int {if st.ix >0{ // if stack not emptyst.ix-- // decrease amount of elements presentelement := st.data[st.ix]st.data[st.ix] = 0return element}return -1 // if stack already empty}func (st Stack) String() string {str := ""for ix := 0; ix < st.ix; ix++ {str += "[" + strconv.Itoa(ix) + ":" + strconv.Itoa(st.data[ix]) + "]"}return str}func main() {st1 := new(Stack)fmt.Printf("%v\n", st1)st1.Push(3) // function call to Pushfmt.Printf("%v\n", st1)st1.Push(7) // function call to Pushfmt.Printf("%v\n", st1)st1.Push(10) // function call to Pushfmt.Printf("%v\n", st1)st1.Push(99) // function call to Pushfmt.Printf("%v\n", st1)p := st1.Pop() // function call to Popfmt.Printf("Popped %d\n", p)fmt.Printf("%v\n", st1)p = st1.Pop() // function call to Popfmt.Printf("Popped %d\n", p)fmt.Printf("%v\n", st1)p = st1.Pop() // function call to Popfmt.Printf("Popped %d\n", p)fmt.Printf("%v\n", st1)p = st1.Pop() // function call to Popfmt.Printf("Popped %d\n", p)fmt.Printf("%v\n", st1)}
Get hands-on with 1400+ tech skills courses.