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/dlist/impl.go

100 lines
1.5 KiB

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