Ad Code

linked List

class Node {
    int data;
    Node next;

    public Node(int data) {
        this.data = data;
        this.next = null;
    }
}

class LinkedList {
    Node head;

    public void insert(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            return;
        }
        Node current = head;
        while (current.next != null) {
            current = current.next;
        }
        current.next = newNode;
    }

    public boolean search(int key) {
        Node current = head;
        while (current != null) {
            if (current.data == key)
                return true;
            current = current.next;
        }
        return false;
    }

    public void delete(int key) {
        if (head == null)
            return;
        if (head.data == key) {
            head = head.next;
            return;
        }
        Node current = head;
        while (current.next != null) {
            if (current.next.data == key) {
                current.next = current.next.next;
                return;
            }
            current = current.next;
        }
    }

    public void displayList() {
        Node current = head;
        while (current != null) {
            System.out.print(current.data + " ");
            current = current.next;
        }
        System.out.println();
    }
}

public class Main {
    public static void main(String[] args) {
        LinkedList linkedList = new LinkedList();

        linkedList.insert(10);
        linkedList.insert(20);
        linkedList.insert(30);
        linkedList.insert(40);

        System.out.print("Linked List: ");
        linkedList.displayList();

        int searchKey = 20;
        if (linkedList.search(searchKey)) {
            System.out.println(searchKey + " found in the linked list");
        } else {
            System.out.println(searchKey + " not found in the linked list");
        }

        int insertValue = 25;
        linkedList.insert(insertValue);
        System.out.print("After inserting " + insertValue + ": ");
        linkedList.displayList();

        int deleteValue = 30;
        linkedList.delete(deleteValue);
        System.out.print("After deleting " + deleteValue + ": ");
        linkedList.displayList();
    }
}
Reactions

Post a Comment

0 Comments