Skip to content

Instantly share code, notes, and snippets.

@iamganeshagrawal
Created May 24, 2023 13:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iamganeshagrawal/90ed73347d283f2ac72e4f9b02834123 to your computer and use it in GitHub Desktop.
Save iamganeshagrawal/90ed73347d283f2ac72e4f9b02834123 to your computer and use it in GitHub Desktop.
Golang | Stack
package main
type node struct {
value interface{}
next *node
}
type Stack interface {
Size() int
IsEmpty() bool
Peek() interface{}
Pop()
Push(v interface{})
}
type stack struct {
head *node
size int
}
func NewStack() Stack {
return &stack{
head: nil,
size: 0,
}
}
func (st *stack) IsEmpty() bool {
return st.size == 0
}
func (st *stack) Peek() interface{} {
if st.head == nil {
return nil
}
return st.head.value
}
func (st *stack) Pop() {
if st.head != nil {
top := st.head
st.head = st.head.next
st.size--
// make it GC colltable
top.next = nil
top.value = nil
}
}
func (st *stack) Push(v interface{}) {
nn := &node{
value: v,
next: nil,
}
nn.next = st.head
st.head = nn
st.size++
}
func (st *stack) Size() int {
return st.size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment