Pregunta

I m building a graph coloring allocator for a toy programming language. While generating spill code sometimes i have to insert before the current instruction a load {for restoring} or an insert after the current instruction { for spilling }. My code is represented as a graph with a node for each basic block and an list of instructions within the block,

I generate a dfs ordered list of graph nodes and for each node i traverse the instruction list within the node, using codeList.listIterator() i can go back and forth via next and previous respectively and do an add for insert after and insert before.

How should the insertion happen right at the beginning of the list using add() method?

¿Fue útil?

Solución

From ListIterator.add API

The element is inserted immediately before the element that would be returned by next(), if any, and after the element that would be returned by previous(), if any. (If the list contains no elements, the new element becomes the sole element on the list.) The new element is inserted before the implicit cursor: a subsequent call to next would be unaffected, and a subsequent call to previous would return the new element. 

Here is an example of how it works in practice

    List<String> l = new ArrayList<String>();
    l.add("1");
    ListIterator<String> i = l.listIterator();
    i.add("2");
    while (i.hasPrevious()) {
        i.previous();
    }
    i.add("3");
    System.out.println(l);

output

[3, 2, 1]

and we could do more tricks with ListIterator

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top