package linkedlist
import "fmt"
type Doubly[T any] struct {
Head *Node[T]
}
func NewDoubly[T any]() *Doubly[T] {
return &Doubly[T]{}
}
func (ll *Doubly[T]) AddAtBeg(val T) {
n := NewNode(val)
n.Next = ll.Head
if ll.Head != nil {
ll.Head.Prev = n
}
ll.Head = n
}
func (ll *Doubly[T]) AddAtEnd(val T) {
n := NewNode(val)
if ll.Head == nil {
ll.Head = n
return
}
cur := ll.Head
for ; cur.Next != nil; cur = cur.Next {
}
cur.Next = n
n.Prev = cur
}
func (ll *Doubly[T]) DelAtBeg() (T, bool) {
if ll.Head == nil {
var r T
return r, false
}
cur := ll.Head
ll.Head = cur.Next
if ll.Head != nil {
ll.Head.Prev = nil
}
return cur.Val, true
}
func (ll *Doubly[T]) DelAtEnd() (T, bool) {
if ll.Head == nil {
var r T
return r, false
}
if ll.Head.Next == nil {
return ll.DelAtBeg()
}
cur := ll.Head
for ; cur.Next.Next != nil; cur = cur.Next {
}
retval := cur.Next.Val
cur.Next = nil
return retval, true
}
func (ll *Doubly[T]) Count() int {
var ctr int = 0
for cur := ll.Head; cur != nil; cur = cur.Next {
ctr += 1
}
return ctr
}
func (ll *Doubly[T]) Reverse() {
var Prev, Next *Node[T]
cur := ll.Head
for cur != nil {
Next = cur.Next
cur.Next = Prev
cur.Prev = Next
Prev = cur
cur = Next
}
ll.Head = Prev
}
func (ll *Doubly[T]) Display() {
for cur := ll.Head; cur != nil; cur = cur.Next {
fmt.Print(cur.Val, " ")
}
fmt.Print("\n")
}
func (ll *Doubly[T]) DisplayReverse() {
if ll.Head == nil {
return
}
var cur *Node[T]
for cur = ll.Head; cur.Next != nil; cur = cur.Next {
}
for ; cur != nil; cur = cur.Prev {
fmt.Print(cur.Val, " ")
}
fmt.Print("\n")
}