How to insert something into a specific position of a mutable LinkedList?

Again, this is similar to what should be obvious.

I would like to insert an item into a linked list at a specific position.

In one case, this field in an element is less than a certain value, so I can do it as follows:

def Add(act:Elem):Unit = {
    val (before, after) = myList.partition(elem.n >= _.n)
    myList = (before :+ act) ++ after
    }

... but this is truly an immutable approach, disguised as volatile. I don’t think I can get a LinkedList node that matches the insertion point, so I cannot mess with the following attribute.

It should not be so difficult. Half of the linked list items are that you insert things in the middle.

I was still messing with the compiler generator (as in this question ). Replacing lists with copies is simply not the way to do this, since there are many recursive calls during which the lists are quite deliberately modified, so you may find that some of the recursive calls still use the list that you just replaced.

I really need volatile lists and simple mutable operations. I think I can write my own collection classes, but I don't think this is unusual. Has anyone already implemented the "correct" multiply-linked lists?

EDIT

Additional Information

. , , , ( , )

Java, , next ( ).

Scala LinkedList node , , , LinkedList node , , . , .

DoublyLinkedList , , , , . , , . . Java/ . Scala DoublyLinkedList node -, . node, .

: -, Trait, ( ). , . , , , (, , "" , "nezt", "" "" ).

, , , (.. ).

+5
3

, LinkedList Buffer, AFAIK . next, . - (, !) , !):

def Add(act: Elem) {
    var last = myList
    while (last.next ne null && last.next.n >= act.n) last = last.next
    var ins = LinkedList(act)
    ins.next = last.next
    last.next = ins
  }

(, myList .

: ; , . ( , last .) . , , .

, , , , ( ).

+4

?

scala> LinkedList(1, 2, 3)
res21: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 3)

scala> val ll = LinkedList(1, 2, 3)  
ll: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 3)

scala> ll.next.insert(LinkedList(0))

scala> ll
res23: scala.collection.mutable.LinkedList[Int] = LinkedList(1, 2, 0, 3)

scala> ll.insert(LinkedList(-1, -2))

scala> ll
res25: scala.collection.mutable.LinkedList[Int] = LinkedList(1, -1, -2, 2, 0, 3)

, , , . .elem , . :

implicit def linkedListToA[A](ll: LinkedList[A]): A = ll.elem
+2

Unpolished version: Inserts otherthe lfirst time the predicate pis true.

import scala.collection.mutable.LinkedList
import scala.annotation.tailrec

val list = LinkedList(1, 2, 3, 10, 11, 12)

def insertAfter[T](l: LinkedList[T], other: LinkedList[T], p: (T) => Boolean) {
  @tailrec
  def loop(x: LinkedList[T]) {
    if (p(x.head)) {
      other.next = x.next
      x.next = other
      return
    }
    if (x.next.isEmpty) {}
    else loop(x.next)
  }
  loop(l)
}

insertAfter(list, LinkedList(100), (_:Int) >= 10)
+1
source

All Articles