Skip to content

Instantly share code, notes, and snippets.

@maxpoletaev
Last active January 15, 2022 20:55
Show Gist options
  • Save maxpoletaev/f06fa8377991a354e33c72222250efd2 to your computer and use it in GitHub Desktop.
Save maxpoletaev/f06fa8377991a354e33c72222250efd2 to your computer and use it in GitHub Desktop.
Go Generic Linked List
package main
type Node[T any] struct {
Val T
Next *Node[T]
}
type LinkedList[T any] struct {
Head *Node[T]
Tail *Node[T]
}
func (l *LinkedList[T]) Add(v T) {
node := &Node[T]{Val: v}
if l.Head == nil {
l.Head = node
}
if l.Tail == nil {
l.Tail = node
} else {
l.Tail.Next = node
l.Tail = node
}
}
func main() {
l := LinkedList[string]{}
l.Add("one")
l.Add("two")
l.Add("three")
node := l.Head
for node != nil {
println(node.Val)
node = node.Next
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment