Efficient implementation of immutable (double) LinkedList

前端 未结 3 1305
难免孤独
难免孤独 2020-11-30 05:12

Having read this question Immutable or not immutable? and reading answers to my previous questions on immutability, I am still a bit puzzled about efficient implementation o

3条回答
  •  执笔经年
    2020-11-30 05:51

    There is a way to emulate "mutation" : using immutable maps.

    For a linked list of Strings (in Scala style pseudocode):

    case class ListItem(s:String, id:UUID, nextID: UUID)

    then the ListItems can be stored in a map where the key is UUID: type MyList = Map[UUID, ListItem]

    If I want to insert a new ListItem into val list : MyList :

    def insertAfter(l:MyList, e:ListItem)={ 
         val beforeE=l.getElementBefore(e)
         val afterE=l.getElementAfter(e)
         val eToInsert=e.copy(nextID=afterE.nextID)
         val beforeE_new=beforeE.copy(nextID=e.nextID)
         val l_tmp=l.update(beforeE.id,beforeE_new)
         return l_tmp.add(eToInsert)
    }
    

    Where add, update, get takes constant time using Map: http://docs.scala-lang.org/overviews/collections/performance-characteristics

    Implementing double linked list goes similarly.

提交回复
热议问题