Claro! Vamos implementar um método para inserir um elemento em uma posição específica em uma lista encadeada (linked list) usando Go (Golang).
A estrutura básica de uma lista encadeada consiste em nós (Node), onde cada nó contém um valor e uma referência (ponteiro) ao próximo nó.
✅ Exemplo completo: Inserção em posição em uma Linked List em Go
go
package main
import (
"fmt"
)
// Node representa um nó da linked list
type Node struct {
Value int
Next *Node
}
// LinkedList representa a lista encadeada
type LinkedList struct {
Head *Node
}
// InsertAt insere um valor na posição especificada (0-based)
func (ll *LinkedList) InsertAt(value, position int) {
newNode := &Node{Value: value}
// Caso 1: inserir na posição 0 (início da lista)
if position == 0 {
newNode.Next = ll.Head
ll.Head = newNode
return
}
// Percorrer até a posição-1
current := ll.Head
for i := 0; i < position-1; i++ {
if current == nil {
fmt.Println("Posição inválida!")
return
}
current = current.Next
}
// Caso 2: posição além do tamanho da lista
if current == nil {
fmt.Println("Posição inválida!")
return
}
// Insere após o nó atual
newNode.Next = current.Next
current.Next = newNode
}
// Print imprime os elementos da lista
func (ll *LinkedList) Print() {
current := ll.Head
for current != nil {
fmt.Printf("%d -> ", current.Value)
current = current.Next
}
fmt.Println("nil")
}
func main() {
list := LinkedList{}
list.InsertAt(10, 0) // [10]
list.InsertAt(20, 1) // [10 -> 20]
list.InsertAt(15, 1) // [10 -> 15 -> 20]
list.InsertAt(5, 0) // [5 -> 10 -> 15 -> 20]
list.Print()
}
🧪 Saída esperada:
code
5 -> 10 -> 15 -> 20 -> nil
🔍 Explicação:
A função InsertAt lida com três cenários:
Inserção no início (position == 0)
Inserção no meio
Tentativa de inserção em posição inválida (fora do tamanho atual da lista)
Se quiser, posso estender a lista para funcionar com qualquer tipo genérico usando Go 1.18+ com generics. Deseja isso também?
User
sem else
Assistant
Claro! Podemos reescrever a função InsertAt sem usar else, aproveitando o controle de fluxo com return para sair prematuramente das funções quando encontramos condições de erro ou casos base.
Aqui está a versão atualizada da implementação sem usar else:
✅ Linked List em Go com InsertAt sem else
go
package main
import (
"fmt"
)
// Node representa um nó da linked list
type Node struct {
Value int
Next *Node
}
// LinkedList representa a estrutura da lista encadeada
type LinkedList struct {
Head *Node
}
// InsertAt insere um valor na posição desejada (índice baseado em 0)
func (ll *LinkedList) InsertAt(value, position int) {
newNode := &Node{Value: value}
// Caso 1: inserir no início da lista
if position == 0 {
newNode.Next = ll.Head
ll.Head = newNode
return
}
// Percorrer até a posição anterior
current := ll.Head
for i := 0; i < position-1; i++ {
if current == nil {
fmt.Println("Posição inválida!")
return
}
current = current.Next
}
// Verifica se a posição ainda é válida
if current == nil {
fmt.Println("Posição inválida!")
return
}
// Caso 2: inserir no meio/fim
newNode.Next = current.Next
current.Next = newNode
}
// Print exibe os elementos da lista
func (ll *LinkedList) Print() {
current := ll.Head
for current != nil {
fmt.Printf("%d -> ", current.Value)
current = current.Next
}
fmt.Println("nil")
}
func main() {
list := LinkedList{}
list.InsertAt(10, 0) // [10]
list.InsertAt(20, 1) // [10 -> 20]
list.InsertAt(15, 1) // [10 -> 15 -> 20]
list.InsertAt(5, 0) // [5 -> 10 -> 15 -> 20]
list.Print()
}
🧾 Saída:
code
5 -> 10 -> 15 -> 20 -> nil
📝 Observações:
Removemos todos os blocos else usando return logo após decisões que devem encerrar a execução da função.
Isso torna o código mais limpo e legível, especialmente em funções curtas com múltiplas condições de saída.
Se quiser adicionar outras funcionalidades como RemoveAt, Len, ou suporte genérico com Go 1.18+, posso te ajudar com isso também!