Created
May 19, 2023 11:50
-
-
Save iamganeshagrawal/06f284ed94c3666f41744e78b811760f to your computer and use it in GitHub Desktop.
Golang | Stack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "errors" | |
type Stack interface { | |
IsEmpty() bool | |
Peek() int | |
Pop() error | |
Push(x int) error | |
Dump() []int | |
} | |
type stack struct { | |
stack []int | |
top int | |
size int | |
} | |
func NewStack(size int) Stack { | |
return &stack{ | |
stack: make([]int, size), | |
size: size, | |
top: -1, | |
} | |
} | |
func (st *stack) IsEmpty() bool { | |
return st.top == -1 | |
} | |
func (st *stack) Peek() int { | |
if st.top == -1 { | |
return -1 | |
} | |
return st.stack[st.top] | |
} | |
func (st *stack) Pop() error { | |
if st.top == -1 { | |
return errors.New("stack underflow") | |
} | |
st.top-- | |
return nil | |
} | |
func (st *stack) Push(x int) error { | |
if st.top+1 == st.size { | |
return errors.New("stack overflow") | |
} | |
st.top++ | |
st.stack[st.top] = x | |
return nil | |
} | |
func (st *stack) Dump() []int { | |
if st.top == -1 { | |
return []int{} | |
} | |
return st.stack[0 : st.top+1] | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"errors" | |
) | |
type StackString interface { | |
IsEmpty() bool | |
Peek() string | |
Pop() error | |
Push(x string) error | |
Dump() []string | |
} | |
type stackstr struct { | |
stack []string | |
top int | |
size int | |
} | |
func NewStackStr(size int) StackString { | |
return &stackstr{ | |
stack: make([]string, size), | |
size: size, | |
top: -1, | |
} | |
} | |
func (st *stackstr) IsEmpty() bool { | |
return st.top == -1 | |
} | |
func (st *stackstr) Peek() string { | |
if st.top == -1 { | |
return "" | |
} | |
return st.stack[st.top] | |
} | |
func (st *stackstr) Pop() error { | |
if st.top == -1 { | |
return errors.New("stack underflow") | |
} | |
st.top-- | |
return nil | |
} | |
func (st *stackstr) Push(x string) error { | |
if st.top+1 == st.size { | |
return errors.New("stack overflow") | |
} | |
st.top++ | |
st.stack[st.top] = x | |
return nil | |
} | |
func (st *stackstr) Dump() []string { | |
if st.top == -1 { | |
return []string{} | |
} | |
return st.stack[0 : st.top+1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment