0

I am trying to implement the set method where you pass in the position in a linked list that you want and the value and the set function adds that value into the position specified in the linked list. I have implemented the set function but for some reason The last element disappears in my implementation. I would greatly appreciate any help. Thanks in advance. I would appreciate any expert eyes that will see what I am missing.


/**
 * A basic singly linked list implementation.
 */
public class SinglyLinkedList<E> implements Cloneable, Iterable<E>, List<E> {
    //---------------- nested Node class ----------------

    /**
     * Node of a singly linked list, which stores a reference to its
     * element and to the subsequent node in the list (or null if this
     * is the last node).
     */
    private static class Node<E> {
       E value;
       Node<E> next;
       public Node(E e) 
       { 
           value = e; 
           next = null; 
       } 
    }
    
    //----------- end of nested Node class -----------

    // instance variables of the SinglyLinkedList
    private Node<E> head = null; // head node of the list (or null if empty)

    private int size = 0; // number of nodes in the list

    public SinglyLinkedList() {
    }              // constructs an initially empty list

    // access methods

    /**
     * Returns the number of elements in the linked list.
     *
     * @return number of elements in the linked list
     */
    public int size() {
        return size;
    }
    /**
     * Adds an element to the end of the list.
     *
     * @param e the new element to add
     */
    public void addLast(E e) {
        // TODO
    }
    /**
     * Tests whether the linked list is empty.
     *
     * @return true if the linked list is empty, false otherwise
     */
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public E get(int i) throws IndexOutOfBoundsException {
        Node<E> a = head;
        if(i<=this.size()) {
            int count = 0;
            while(count < i) {
                count ++;
                a = a.next;
            }
            return a.value;
        }

        return null;
    }

    @Override
    public E set(int i, E e) throws IndexOutOfBoundsException {
        Node<E> current = head;
        Node<E> setNode = new Node<E>(e);
        if(i==0) {
            this.addFirst(e);
        }
        else if(i==this.size){
            this.addLast(e);
        }
        else {
            for(int j=0; current != null && j < (i-1);j++) {
                current = current.next;
            }
            Node<E> temp = current.next;
            current.next = setNode;
            setNode.next = temp;
        }
        return setNode.value;
        }
    
    

    

   

    // update methods

    /**
     * Adds an element to the front of the list.
     *
     * @param e the new element to add
     */
    public void addFirst(E e) {
        Node<E> first = new Node<>(e);
        first.next = this.head;
        this.head = first;
        this.size++;
    }

   

    
    @SuppressWarnings({"unchecked"})
    public boolean equals(Object o) {
        // TODO
        return false;   // if we reach this, everything matched successfully
    }

    @SuppressWarnings({"unchecked"})
    public SinglyLinkedList<E> clone() throws CloneNotSupportedException {
        // TODO
        return null;
    }


    /**
     * Produces a string representation of the contents of the list.
     * This exists for debugging purposes only.
     * @return 
     */
    public String toString() {
        for(int i=0;i<this.size();i++) {
            System.out.println(this.get(i));
        }
        return "end of Linked List";
    }

    public static void main(String[] args) {
        
            SinglyLinkedList <Integer> ll =new SinglyLinkedList <Integer>();
            ll.addFirst(5);
            ll.addFirst(4);
            ll.addFirst(3);
            ll.addFirst(2);
            ll.set(1,0);
            System.out.println(ll);
        }
    }
Jim Morrison
  • 2,784
  • 1
  • 7
  • 11
mohelt
  • 55
  • 2
  • 6
  • 1
    can you add `addLast` implementation? It is missing in the above code. Also, you are not updating the size inside the `set` methods `for` loop – Thiyanesh Jan 31 '21 at 20:54
  • Yes, turns out the problem was incrementing the size. Thanks a bunch. – mohelt Jan 31 '21 at 21:00

2 Answers2

1

Assumptions

  1. addLast method is missing in the code
  2. The error could be there too

Known cause

This code is not incrementing the size inside the set method's for loop.The size is incremented in addLast(possibly) and addFirst and not incremented in other case (final else part)

Thiyanesh
  • 2,360
  • 1
  • 4
  • 11
0

It is not clear what is planned to do with set method. The way it is implemented now, it behaves more like insert, meaning that it will add new node, bit it does not increase the total count of elements (size).

It the set method is changing the value of the node, which name indicates, then this part is wrong:

else {
    for(int j=0; current != null && j < (i-1);j++) {
        current = current.next;
    }
    Node<E> temp = current.next;
    current.next = setNode;
    setNode.next = temp;
}

It should replace the value instead of adding the new one:

else {
    for(int j=0; current != null && j < (i-1);j++) {
        current = current.next;
    }
    current.value=e
}

Also, it looks like the index i is 1-based, while everything else is 0 based. I didn't check the code above, but the concept should be like shown.

mnikolic
  • 572
  • 1
  • 5
  • 9