Saurav Shrivastav
Saurav Shrivastav

Reputation: 61

Custom Linked List in Java

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;
        }
    }

}

Upvotes: 1

Views: 1265

Answers (1)

singh.indolia
singh.indolia

Reputation: 1291

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.

Upvotes: 2

Related Questions