Skip to content

Instantly share code, notes, and snippets.

@gabrielbussolo
Created September 9, 2023 15:31
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 gabrielbussolo/6e05a9c432a23472160e641273757d37 to your computer and use it in GitHub Desktop.
Save gabrielbussolo/6e05a9c432a23472160e641273757d37 to your computer and use it in GitHub Desktop.
Stack implementation using linked list in golang
package main
import (
"fmt"
)
type Node struct {
Data int
Next *Node
}
type Stack struct {
Head *Node
}
func (s *Stack) Push(data int) {
newNode := Node{Data: data}
if s.Head == nil {
s.Head = &newNode
return
}
newNode.Next = s.Head
s.Head = &newNode
}
func (s *Stack) Pop() *int {
if s.Head == nil {
return nil
}
data := s.Head.Data
s.Head = s.Head.Next
return &data
}
func (s *Stack) Peek() *int {
if s.Head == nil {
return nil
}
return &s.Head.Data
}
func (s *Stack) Lookup(position int) *int {
if s.Head == nil {
return nil
}
current := s.Head
for i := 0; i < position; i++ {
current = current.Next
if current == nil {
return nil
}
}
return &current.Data
}
func (s *Stack) Display() {
current := s.Head
for current != nil {
fmt.Printf("%d -> ", current.Data)
current = current.Next
}
fmt.Println("nil")
}
func main() {
s := &Stack{}
s.Push(1)
s.Push(2)
s.Push(3)
s.Push(4)
s.Display()
l := s.Lookup(3)
if l != nil {
fmt.Println(*l)
} else {
fmt.Println("not found")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment