These are small simple implementations of many Data Structures and Algorithms using Go. I'm doing this to refresh my memory of them, and to learn Go better.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
go-dsa-study/llist/impl.go

106 lines
1.5 KiB

package llist
import (
"fmt"
)
type Node struct {
Data any
Next *Node
}
type LinkedList struct {
Front *Node
End *Node
Count int
}
func (l *LinkedList) Add(data any) {
el := Node{data, nil}
if l.Front == nil {
l.Front = &el
l.End = &el
} else {
l.End.Next = &el
l.End = &el
}
l.Count++
}
func (l *LinkedList) Find(data any) (*Node) {
for el := l.Front; el != nil; el = el.Next {
if el.Data == data {
return el
}
}
return nil
}
func (l *LinkedList) Delete(target *Node) {
if l.Front == target {
l.PopFront()
} else if l.End == target {
l.PopBack()
} else {
el := l.Front
for el.Next != target {
el = el.Next
}
el.Next = el.Next.Next
target.Next = nil
l.Count--
}
}
func (l *LinkedList) PopBack() (*Node) {
el := l.End
if l.Front == nil {
return nil
} else if l.Front == l.End {
l.Front = nil
l.End = nil
l.Count--
} else {
new_end := l.Front
for new_end.Next.Next != nil {
new_end = new_end.Next
}
l.End = new_end
l.End.Next = nil
l.Count--
}
return el
}
func (l *LinkedList) PopFront() (*Node) {
el := l.Front
if l.Front == nil {
return nil
} else if l.Front == l.End {
l.Front = nil
l.End = nil
l.Count--
} else {
l.Front = l.Front.Next
l.Count--
}
return el
}
func (l *LinkedList) Dump() {
fmt.Println("----------------", l.Count, "nodes")
for cur := l.Front; cur != nil; cur = cur.Next {
fmt.Println(cur.Data)
}
}