1

I am trying to implement my own LinkedList class which adds and deletes node. The only issue I am facing is, when I am trying to print all the nodes of the linked list, I am not able to print the last node because of my while loop. I am not sure how to remove this bug/error.

public class LinkedList {
    private Node head;

    public static void main(String[] args) {
        LinkedList list = new LinkedList();

        list.insert(5);
        list.insert(10);
        list.insert(13);
        list.insert(15);
        list.insert(20);

        list.show();

        list.delete(13);
        list.show();
    }

    public void insert(int val) {
        Node node = new Node(val);
        node.next = null;
        if (head == null) {
            head = node;
        } else {
            Node temp = head;
            while (temp.next != null) {
                temp = temp.next;
            }
            temp.next = node;
        }
    }

    public void delete(int val) {
        Node temp = head, prev = null;

        if (temp != null && temp.val == val) {
            head = temp.next;
            return;
        }

        while (temp != null && temp.val != val) {
            prev = temp;
            temp = temp.next;
        }
        if (temp == null) return;
        
        prev.next = temp.next;
    }

    public void show() {
        Node temp = head;
        while (temp.next != null) {
            System.out.print(temp.val + " ");
            temp = temp.next;
        }
        System.out.println();
    }

    private class Node {
        Node next;
        int val;

        private Node(int val) {
            this.val = val;
        }
    }

}
2
  • 1
    Hint: figuring "why is my code not doing what I expect it to do" is a crucial part of learning programming. So: the very first step for you is to be able to follow what your code is doing. You can get there by A) learning how to use a debugger (really easy with an IDE like intellij or eclipse) or B) by simply adding PRINT statements. And then, also very helpful for such small pieces of code: take a piece of paper, and a pen. And then "run" your code mentally. Write down variable names, and then, write down what changes, etc. Commented Aug 20, 2021 at 8:36
  • You are very welcome. Commented Aug 20, 2021 at 9:17

1 Answer 1

2

As per your code and I am only focusing your show() method so you can change like:

 public void show() {
        Node temp = head;
        while (temp != null) {
            System.out.print(temp.val + " ");
            temp = temp.next;
        }
        System.out.println();
    }

and this can easily captured via debugger. I hope this will help you out. For more please let me know.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.