Created
October 23, 2022 20:17
-
-
Save flrdv/f28fc4908929fc60b785ea11fe784013 to your computer and use it in GitHub Desktop.
Simple unidirectional generic linked list with implemented reversing
This file contains hidden or 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[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