Java: Linked Lists Implementation

Java

Video is ready, Click Here to View ×


Learn how to implement a linked list class in Java. Download the example code here, github.com/joeyajames/java

13 thoughts on “Java: Linked Lists Implementation

  1. Your code will fail if you try to remove the first element of the list

    Correct code

    Node thisNode = root;
    Node prevNode = null;
    //Considering first element to be the data
    if(thisNode.getData()==data)
    {
    root = thisNode.getNextNode();
    thisNode.setNextNode(null);
    this.setSize(this.getSize()-1);
    return true;
    }
    prevNode=thisNode;
    thisNode=thisNode.getNextNode();
    //considering the rest of the elements except the last
    while(thisNode!=null ){
    if(thisNode.getData()==data){
    prevNode.setNextNode(thisNode.getNextNode());
    thisNode.setNextNode(null);
    this.setSize(this.getSize()-1);
    return true;
    }
    prevNode=thisNode;
    thisNode=thisNode.getNextNode();
    }

    return false;

  2. In the video, 5:55 remove() method, what if the node which we are looking to remove happens to be the first node i.e root node. I am confused how this statement will execute PrevNode.setNextNode(thisNode.getNextNode()). because we have mentioned prevNode = null; since there is no node. Other Than that, Thanks for your excellent video and explanation.

  3. Hi Joe, thank you for this example. I suggest you to fix your remove method, because we can easily get NullPointerException. Example : LinkedList list = new LinkedList();
    list.add(1) than list.remove (1) -> NullPointerException.

Leave a Reply

Your email address will not be published. Required fields are marked *