package linkedlist
import (
"fmt"
)
type List []Element
type Element struct {
value int
next *Element
}
func New(elements []int) *List {
list := make(List, len(elements))
for i, elem := range elements {
list[i] = Element{value: elem, next: nil}
if i != 0 {
list[i].next = &list[i-1]
}
}
return &list
}
func (l *List) Size() int {
return len(*l)
}
func (l *List) Push(element int) {
next := Element{element, nil}
if len(*l) > 0 {
(*l)[len(*l)-1].next = &next
}
*l = append(*l, next)
}
func (l *List) Pop() (int, error) {
if len(*l) < 1 {
return 0, fmt.Errorf("could not Pop() from empty list")
}
ret := (*l)[len(*l)-1].value
*l = (*l)[:len(*l)-1]
return ret, nil
}
func (l *List) Array() []int {
ret := make([]int, len(*l))
for i, elem := range *l {
ret[i] = elem.value
}
return ret
}
func (l *List) Reverse() *List {
tmp := make([]int, len(*l))
for i := len(*l) - 1; i >= 0; i-- {
tmp[len(*l)-1-i] = (*l)[i].value
}
return New(tmp)
}