Last active
January 15, 2022 20:55
-
-
Save maxpoletaev/f06fa8377991a354e33c72222250efd2 to your computer and use it in GitHub Desktop.
Go Generic Linked List
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[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