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

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

    My solution is not as clean as it will be with recursion but if you are testing more than 50,000 elements on the list go with an iterative solution. or you can modify the JVM and change the stack size. Because you can get a stack overflow just because you will pass the capacity of activation records in the stack. Think about the worst case scenario that you will do an insert at the end of the list.

    /**
     * Inserts the specified element at the specified position in this list.
     *
     * @param :index the desire position starting from 0 2,3,4,5
     * @param :data  the content of the new node
     * @return Boolean: if the insertion was successfully return true otherwise false
     */
    public boolean add(int index, T data) {
        /*Add to the end of the list*/
        if (index == size()) {
            add(data);
            return true;
        }
        /*Empty list and index bigger than 0*/
        else if (this.front == null && index != 0) {
            return false;
        } else {
            Node<T> tempNode = this.front;
    
            while (tempNode != null && tempNode.next != null && --index != 0) {
                tempNode = tempNode.next;
            }
    
            if (index != 0) {
                return false;
            } else {
                Node<T> newNode = new Node<T>(data);
    
                /*Empty list,and index is 0*/
                if (tempNode == null) {
                    this.front = newNode;
                } else {
                    newNode.next = tempNode.next;
                    tempNode.next = newNode;
                }
            }
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题