Puppollo
6/9/2017 - 8:48 AM

Linked list

Linked list

package main

import (
	"strconv"
)

type (
	Value struct {
		value int
	}

	Node struct {
		Key  int
		Value
		next *Node
		prev *Node
	}

	List struct {
		head    *Node
		tail    *Node
		current *Node
	}
)

func (v Value) String() string {
	return strconv.Itoa(v.value)
}

func (l *List) Add(value Value) {
	node := Node{
		Value: value,
		prev: nil,
		next: nil,
	}

	if l.head == nil {
		node.Key = 0
		l.head = &node
		l.tail = &node
		return
	}

	node.Key = l.tail.Key + 1
	node.prev = l.tail
	l.tail.next = &node
	l.tail = &node
}

func (l List) Current() *Value {
	return &l.current.Value
}

func (l *List) Next() bool {
	if l.current == nil {
		l.current = l.head
		return true
	}
	l.current = l.current.next
	return l.current != nil
}

func (l *List) Prev() bool {
	if l.current == nil {
		l.current = l.tail
		return true
	}
	l.current = l.current.prev
	return l.current != nil
}

func main() {
	list := List{}
	list.Add(Value{2})
	list.Add(Value{3})
	list.Add(Value{1})
	list.Add(Value{15})

	for list.Next() {
		println(list.Current().String())
	}

	for list.Prev() {
		println(list.Current().String())
	}
}