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

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

    You should do something like this:

    public void insert (Object item, int pos)
    {
        Link add = new Link();
        int ix = pos - 1;
        Link cur = _head;
        for (int i = 0; i < _list_size; i++) {
          if(i == ix) {
            add.next = cur.next;
            cur.next = add;
          }
          cur = cur.next;
        }
       ++_listsize;
     }
    

提交回复
热议问题