Skip to content

Instantly share code, notes, and snippets.

@flrdv
Created October 23, 2022 20:17
Show Gist options
  • Select an option

  • Save flrdv/f28fc4908929fc60b785ea11fe784013 to your computer and use it in GitHub Desktop.

Select an option

Save flrdv/f28fc4908929fc60b785ea11fe784013 to your computer and use it in GitHub Desktop.
Simple unidirectional generic linked list with implemented reversing
package main
import "fmt"
type Node[T any] struct {
payload T
next *Node[T]
}
func NewLList[T any](firstElem T) *Node[T] {
return &Node[T]{
payload: firstElem,
}
}
func (n *Node[T]) Append(payload T) *Node[T] {
tail := n
for tail.next != nil {
tail = tail.next
}
tail.next = &Node[T]{
payload: payload,
}
return tail
}
func (n *Node[T]) Walk(iterator func(T) (shouldContinue bool)) bool {
node := n
for node.next != nil {
if !iterator(node.payload) {
return false
}
node = node.next
}
return iterator(node.payload)
}
func (n *Node[T]) Tail() *Node[T] {
node := n
for node.next != nil {
node = node.next
}
return node
}
func (n *Node[T]) Reverse() *Node[T] {
if n.next == nil {
return n
}
prev, curr := n, n.next
prev.next = nil
for curr.next != nil {
next := curr.next
curr.next = prev
prev, curr = curr, next
}
curr.next = prev
return curr
}
func main() {
list := NewLList("hello")
list.Append("world")
list.Append("illya")
list.Walk(func(s string) bool {
fmt.Println(s)
return true
})
fmt.Println("--- Reversing ---")
reversed := list.Reverse()
reversed.Walk(func(s string) bool {
fmt.Println(s)
return true
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment