Created
September 9, 2023 15:31
-
-
Save gabrielbussolo/6e05a9c432a23472160e641273757d37 to your computer and use it in GitHub Desktop.
Stack implementation using linked list in golang
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 ( | |
"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 ¤t.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