Skip to content

Instantly share code, notes, and snippets.

@anisbhsl
Created November 17, 2022 15:56
Show Gist options
  • Save anisbhsl/56e03bab6d7b224d21126860a9476292 to your computer and use it in GitHub Desktop.
Save anisbhsl/56e03bab6d7b224d21126860a9476292 to your computer and use it in GitHub Desktop.
Simple Stack Implementation in Go
package main
import (
"fmt"
)
type Node struct{
data int
next *Node
}
type Stack struct{
head *Node
length int
}
func (s *Stack) Push(node Node){
s.length+=1
tmp := s.head
s.head=&node
node.next=tmp
}
func (s *Stack) Pop() *Node{
if s.isEmpty(){
return nil
}
nextNode := s.head.next
popNode := s.head
s.length-=1
s.head=nextNode
return popNode
}
func (s *Stack) Peek() *Node{
if s.isEmpty(){
return nil
}
return s.head
}
func (s *Stack) isEmpty() bool{
return s.length==0
}
func main() {
stack := Stack{
length:0,
}
fmt.Println(stack.isEmpty())
n1 := Node{
data: 5,
}
n2 := Node{
data:6,
}
stack.Push(n1)
stack.Push(n2)
fmt.Println(stack.isEmpty())
fmt.Println(stack.length)
stack.Pop()
fmt.Println(stack.length)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment