emirpasic / gods

GoDS (Go Data Structures) - Sets, Lists, Stacks, Maps, Trees, Queues, and much more
Other
16.32k stars 1.77k forks source link

RedBlackTree: Iterators become invalid after removing an element. #223

Open 981377660LMT opened 1 year ago

981377660LMT commented 1 year ago
package main

import (
    "fmt"

    "github.com/emirpasic/gods/trees/redblacktree"
)

func main() {
    tree := redblacktree.NewWithIntComparator()
    tree.Put(1, struct{}{})
    tree.Put(2, struct{}{})
    tree.Put(3, struct{}{})
    it1 := tree.Iterator()
    it2 := tree.Iterator()
    it1.Next()
    it2.Next()
    it2.Next()
    fmt.Println(it1.Key()) // 1 
    tree.Remove(2)
    fmt.Println(it1.Key()) // 1 
    it1.Next()
    fmt.Println(it1.Key()) 
        //  need to be 3 here
        // panic: runtime error: invalid memory address or nil pointer dereference
}

I think that after removing an element, the iterators of the other elements need to be unaffected.

amoyraku commented 1 year ago

You can not remove elements while you are using a iterator. You will make the iterator become invalid, then any operation on the iterator will cause a problem.

PapaCharlie commented 1 year ago

FWIW, when you use an iterator over a collection in Java, the returned iterator supports deleting the most recently returned element. Might be an acceptable way to support deletion during iteration? https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#remove--