Created
May 20, 2025 14:04
-
-
Save senapk/da9dcad6f064034a0abd74459bb67a9e to your computer and use it in GitHub Desktop.
Lista dupla com iteradores e template
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
type Node[T comparable] struct { | |
Value T | |
next *Node[T] | |
prev *Node[T] | |
root *Node[T] | |
} | |
func NewNode[T comparable]() *Node[T] { | |
return &Node[T]{} | |
} | |
func (n *Node[T]) Next() *Node[T] { | |
if n == n.root { | |
return n.root | |
} | |
if n.next == n.root { | |
return n.root.next | |
} | |
return n.next | |
} | |
type List[T comparable] struct { | |
root *Node[T] | |
} | |
func NewList[T comparable]() *List[T] { | |
root := NewNode[T]() | |
root.next = root | |
root.prev = root | |
root.root = root | |
return &List[T]{root: root} | |
} | |
func (l *List[T]) Front() *Node[T] { | |
if l.root.next == l.root { | |
return nil | |
} | |
return l.root.next | |
} | |
func (l *List[T]) End() *Node[T] { | |
return l.root | |
} | |
func (l *List[T]) PushBack(value T) { | |
l.Insert(l.root, value) | |
} | |
func (l *List[T]) Insert(n *Node[T], value T) { | |
node := NewNode[T]() | |
node.Value = value | |
node.root = l.root | |
node.prev = n.prev | |
node.next = n | |
n.prev.next = node | |
n.prev = node | |
} | |
func main() { | |
// var mapa map[int]string = make(map[int]string) | |
// mapa[5] = "banana" | |
list := NewList[string]() | |
list.PushBack("one") | |
list.PushBack("two") | |
list.PushBack("three") | |
i := 0 | |
for n := list.Front(); i < 100; n = n.Next() { | |
fmt.Println(n.Value) | |
i += 1 | |
} | |
} | |
// package main | |
// import ( | |
// "container/list" | |
// "fmt" | |
// ) | |
// func main() { | |
// list := list.New() | |
// for i := range 10 { | |
// list.PushBack(i) | |
// } | |
// for n := list.Front(); n != nil; n = n.Next() { | |
// fmt.Println(n.Value.(int)) | |
// } | |
// } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment