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

后端 未结 7 1360
天命终不由人
天命终不由人 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:38

    Use add( int index, E element), which insert the element at the specified index : http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html#add(int, E)

    EDIT : if you're using LinkedList, of course ; with your own class, you have to store prev/next pointers and simply update them (previous node next's pointer should point to the new element, and next node previous's pointer should point to the new element too)

提交回复
热议问题