Why Linked Lists Are Different from Arrays

java dev.to


Arrays are great for fast access…

But inserting or deleting elements can be expensive.

That’s where Linked Lists become powerful.

A Singly Linked List connects nodes like a chain:

  • each node points only to the next node.

1. Structure of a Singly Linked List

Visual representation:

[10] → [20] → [30] → null

Each node contains:

  • data
  • reference to next node

2. Insert at Head
Idea

New node becomes the first node.

public void insertAtHead(int data) {

Node newNode = new Node(data);

newNode.next = head;

head = newNode;
Enter fullscreen mode Exit fullscreen mode

}

Complexity

O(1) insertion at head

Because:

  • no traversal needed

3. Insert at End
Idea

Traverse until last node.

public void insertAtEnd(int data) {

Node newNode = new Node(data);

if (head == null) {
    head = newNode;
    return;
}

Node temp = head;

while (temp.next != null) {
    temp = temp.next;
}

temp.next = newNode;
Enter fullscreen mode Exit fullscreen mode

}

Complexity

O(n) insertion at end

Because:

  • traversal is required.

4. Delete a Node
Idea

Find previous node,
then bypass target node.

public void delete(int key) {

if (head == null)
    return;

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

Node temp = head;

while (temp.next != null &&
       temp.next.data != key) {

    temp = temp.next;
}

if (temp.next != null) {
    temp.next = temp.next.next;
}
Enter fullscreen mode Exit fullscreen mode

}
5. Traversal
Idea

Move node by node until null.

public void printList() {

Node temp = head;

while (temp != null) {

    System.out.print(temp.data + " -> ");

    temp = temp.next;
}

System.out.println("null");
Enter fullscreen mode Exit fullscreen mode

}

Linked Lists trade:

  • random access

for:

  • flexible insertions/deletions

That’s their main strength.

  • Nodes form a one-way chain
  • Head stores first node
  • Insert at head → O(1)
  • Traversal → O(n)

Singly Linked Lists are one of the most important DSA foundations.

Understanding them deeply makes advanced structures much easier

Explore More: https://www.quipoin.com/tutorial/data-structure-with-java/singly-linked-list

Source: dev.to

arrow_back Back to Tutorials