Linked List Implementation in Java Using Arrays

In this blog post, we will learn how to implement Linked List in Java using Arrays.

Understanding the Concept

The idea is to simulate pointers (or links) using array indices. Each "node" will be represented as an element in the array, and instead of holding a reference to the next node, it will store the index of the next element. 

Java Implementation: 

Here's a simple version of a singly linked list implemented using arrays:

class LinkedList {
    private int[] data;
    private int[] next;
    private int head;
    private int freeIndex;

    public LinkedList(int size) {
        data = new int[size];
        next = new int[size];
        for (int i = 0; i < size - 1; i++) {
            next[i] = i + 1;
        }
        next[size - 1] = -1;
        head = -1;
        freeIndex = 0;
    }

    // Insert a new element at the beginning
    public void insert(int value) {
        if (freeIndex == -1) {
            throw new IllegalStateException("List is full");
        }

        int newIndex = freeIndex;
        freeIndex = next[newIndex];

        data[newIndex] = value;
        next[newIndex] = head;
        head = newIndex;
    }

    // Print the list
    public void printList() {
        int curr = head;
        while (curr != -1) {
            System.out.print(data[curr] + " -> ");
            curr = next[curr];
        }
        System.out.println("null");
    }
}

Testing the Linked List Implementation:

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

        list.insert(10);
        list.insert(20);
        list.insert(30);

        list.printList(); // 30 -> 20 -> 10 -> null
    }
}

Output:

30 -> 20 -> 10 -> null

Advantages and Limitations 

Advantages: 

Predictable Memory Usage: The amount of memory used is fixed and determined at the start. 

Random Access: O(1) time complexity for accessing elements. 

Limitations: 

Fixed Size: Unlike the standard linked list, our array-backed version has a fixed size. 

Complex Insertions and Deletions: Especially if performed in the middle. 

Conclusion

Implementing a linked list using an array in Java might not be the most efficient or typical approach for most applications. However, this exercise provides valuable insights into how data structures can be molded and adapted to fit various constraints and requirements. Understanding these concepts can help in algorithm design, problem-solving, and seeing the flexibility within seemingly rigid structures.

Comments