Simple LinkedList program in Java

LinkedList in Java is a doubly-linked list implementation that allows for efficient insertion and removal of elements at the cost of slower random access. It implements the List interface and can be used as a stack, queue, or double-ended queue (deque).
Create a LinkedList and add three data and remove the second data from the list and print it.

Solutions:


class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}
class LinkedList {
    private Node head;

    // Constructor
    public LinkedList() {
        this.head = null;
    }

    // Add a node to the end of the list
    public void add(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
    }

    // Remove a node from the list
    public void remove(int data) {
        if (head == null) return;

        if (head.data == data) {
            head = head.next;
            return;
        }

        Node current = head;
        while (current.next != null && current.next.data != data) {
            current = current.next;
        }

        if (current.next != null) {
            current.next = current.next.next;
        }
    }

    // Display the list
    public void display() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " -> ");
            current = current.next;
        }
        System.out.println("null");
    }

    // Find a node in the list
    public boolean find(int data) {
        Node current = head;
        while (current != null) {
            if (current.data == data) {
                return true;
            }
            current = current.next;
        }
        return false;
    }
}
public class Main {
    public static void main(String[] args) {
        LinkedList list = new LinkedList();
        list.add(10);
        list.add(20);
        list.add(30);

        System.out.println("Original List:");
        list.display();

        list.remove(20);
        System.out.println("List after removing 20:");
        list.display();

        System.out.println("Finding 10: " + list.find(10));
        System.out.println("Finding 40: " + list.find(40));
    }
}

Leave a Comment

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

Scroll to Top