简体   繁体   中英

Implementing special linked-list method in Java

Is it possible to create a linked list in Java, with the ability to add new links anywhere in the middle (not just at the beginning or end) of the list -- if possible, without copy-pasting in memory large parts of the list to accommodate for entry of a new link?

If so, please post your example!!

You can use LinkedList to do this.

List<Integer> ints = new LinkedList<Integer>();
for (int i = 0; i <= 10; i++)
    ints.add(i / 2, i);
System.out.println(ints);

prints

[1, 3, 5, 7, 9, 10, 8, 6, 4, 2, 0]

As you can see it has been adding entries in the middle of the list.

Java中的LinkedList类已经通过其add(index, element)方法实现了这一点。

In pseudo code something link this is a good place to start:

public LinkedList<E> implements List<E>{
    ...

    public void add(int index, E element){
        Node<E> current=findNodeAt(index);
        //add in your logic to insert this node at this location
        //probably something like (depending on your linking)
        element.setNext({current nodes next value})
        current.setnext(element);      
    }

    private Node<E> findNodeAt(index){
        //iterate through list until you reach the index or end of the list
        //then return that node
    }

    ...
}





public Node<E>{
    private Node<E> next;
    ... 

    Node<E> setNext(Node<E> next){
        Node<E> previousNext=next;
        this.next=next;
        return previousNext;
    }

    ...
}

LinkedList实现'List'接口,它有你需要的add方法: http//docs.oracle.com/javase/7/docs/api/java/util/List.html#add%28int,%20E%29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM