Monday, 14 July 2025

Create custom LinkedList with add, remove functionality

 ✅ What is a LinkedList?

A LinkedList is a linear data structure where each element (called a node) contains:

  • data

  • a reference (link) to the next node in the list.


✅ Node Structure

Each Node contains:

java
T data; // The value Node<T> next; // Pointer to next node

✅ LinkedList Operations

1. Add (at end)add(T data)

  • Create a new node.

  • If the list is empty, set head = newNode.

  • Otherwise, traverse to the last node and set its next to the new node.

2. Remove (by value)remove(T data)

  • Check if head is null → return false.

  • If head.data == data, remove it by head = head.next.

  • Otherwise, traverse until current.next.data == data, then skip it by current.next = current.next.next.


✅ Java Code – Custom LinkedList

java
public class CustomLinkedList<T> { private Node<T> head; private static class Node<T> { T data; Node<T> next; Node(T data) { this.data = data; } } // Add element at end public void add(T data) { Node<T> newNode = new Node<>(data); if (head == null) { head = newNode; } else { Node<T> current = head; while (current.next != null) { current = current.next; } current.next = newNode; } } // Remove element by value public boolean remove(T data) { if (head == null) return false; if (head.data.equals(data)) { head = head.next; return true; } Node<T> current = head; while (current.next != null && !current.next.data.equals(data)) { current = current.next; } if (current.next == null) return false; current.next = current.next.next; return true; } // Display list public void display() { Node<T> current = head; while (current != null) { System.out.print(current.data + " -> "); current = current.next; } System.out.println("null"); } }

✅ Main Method to Test

java
public class Main { public static void main(String[] args) { CustomLinkedList<Integer> list = new CustomLinkedList<>(); list.add(10); list.add(20); list.add(30); list.display(); // 10 -> 20 -> 30 -> null list.remove(20); list.display(); // 10 -> 30 -> null } }

No comments:

Post a Comment