I need help understanding how this linked list set method wo

I need help understanding how this linked list set method works in java,

     * Set value stored at location i to object o, returning old value.
     *
     * @pre 0 <= i < size()
     * @post sets ith entry of list to value o, returns old value
     * @param i location of entry to be changed.
     * @param o new value
     * @return former value of ith entry of list.
     */
    public E set(int i, E o)
    {
        if (i >= size()) return null;
        Node<E> finger = head;
        // search for ith element or end of list
        while (i > 0)
        {
            finger = finger.next();
            i--;
        }
        // get old value, update new value
        E result = finger.value();
        finger.setValue(o);
        return result;

Solution

Hi friend,

Please go through comment, you can uderstand logic of set method.

    public E set(int i, E o)
{
   // if given position number (i) is greater than current size of list,
   // then you can not set, because this is not valid position, so return null
if (i >= size()) return null;


Node<E> finger = head; // initializing finger with head node of list

// search for ith element or end of list
while (i > 0) // traverse until we not hit ith node in list
{
finger = finger.next();
i--;
}

// now after above while loop, finger points ith node in list

// get old value, update new value
E result = finger.value(); // getting old value of ith node
finger.setValue(o); // setting new value in ith node
return result;
}

I need help understanding how this linked list set method works in java, * Set value stored at location i to object o, returning old value. * * @pre 0 <= i &

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site