Created
May 24, 2023 13:12
-
-
Save iamganeshagrawal/90ed73347d283f2ac72e4f9b02834123 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 | |
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