Skip to content

Java Link List Implementation

My linked list implementation

public class LinkList {

    static Node head;  // Renamed 'list' to 'head' for clarity
    static int size = 0;

    // Inner class for Node
    static class Node {
        String data;  // Directly storing string data for simplicity
        Node next;

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

    // Method to add a new node
    public void add(String str) {
        Node node = new Node(str);
        if (head == null) {
            head = node;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = node;
        }
        size++;
    }

    // Method to delete a node at a given index
    public void delete(int index) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException("Index out of bounds");
        }
        if (index == 0) {
            head = head.next;
            return;
        }
        Node current = head;
        for (int i = 0; i < index - 1; i++) {
            current = current.next;
        }
        current.next = current.next.next;
        size--;
    }

    // Method to insert a node at a given index
    public void insert(int index, String str) {
        if (index > size || index < 0) {
            throw new IndexOutOfBoundsException("Index out of bounds");
        }
        Node node = new Node(str);
        if (index == 0) {
            node.next = head;
            head = node;
        } else {
            Node current = head;
            for (int i = 0; i < index - 1; i++) {
                current = current.next;
            }
            node.next = current.next;
            current.next = node;
        }
        size++;
    }

    // Method to convert linked list to string
    @Override
    public String toString() {
        StringBuilder str = new StringBuilder();
        Node current = head;
        while (current != null) {
            str.append(current.data).append("\t");
            current = current.next;
        }
        return str.toString();
    }

    public static void main(String[] args) {
        LinkList list = new LinkList();
        list.add("Hello");
        list.add("World");
        list.insert(1, "Java");
        list.delete(2);

        System.out.println(list);
    }
}

Stay updated!

Receive insights on tech, leadership, and growth.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.