How to insert an item at a given position in a linked list?

后端 未结 7 1359
天命终不由人
天命终不由人 2021-01-21 12:50

This how you would add an item:

public void insert (Object item)
{
    Link add = new Link();
    add.data = item;
    add.next = head;
    _head = add;
    ++_l         


        
7条回答
  •  失恋的感觉
    2021-01-21 13:30

    After attempting alone the implementation of the concept, you can consider the open-source research. One of the best things you can do with open source is learn from it, study the implementation of java.util.LinkedList,

    following the logic of the method add (int index, E element) { http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/LinkedList.java#360 }, you can divide in;

    1) Get where the element will be added, in your case "link" http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/LinkedList.java#380

    2) and you can examine the code that links the elements following the logic "before adding" in the code snippet http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/LinkedList.java#794

    So, you will understand the logic behind the algorithm and will be able to perform your own implementation

提交回复
热议问题