WikiGalaxy

Personalize

Linked Lists in Java

Introduction:

A linked list is a linear data structure where elements are stored in nodes, with each node pointing to the next. This structure allows for efficient insertion and deletion of elements.

Types of Linked Lists:

There are several types of linked lists, including singly linked lists, doubly linked lists, and circular linked lists. Each type has its own use cases and benefits.

Advantages:

Linked lists offer dynamic sizing and efficient insertions/deletions, making them ideal for scenarios where these operations are frequent.

Disadvantages:

They require more memory than arrays due to the storage of pointers, and accessing elements by index is less efficient.

    Step 1: Node creation - Each element is stored in a node.
    Step 2: Linking nodes - Each node points to the next node.
    Step 3: Head and Tail - The first node is the head, and the last node is the tail.
    Step 4: Traversal - Navigate through the list from head to tail.
  

      class Node {
          int data;
          Node next;
          Node(int d) { data = d; next = null; }
      }
      public class LinkedList {
          Node head;
          public void add(int data) {
              Node newNode = new Node(data);
              if (head == null) {
                  head = newNode;
              } else {
                  Node temp = head;
                  while (temp.next != null) {
                      temp = temp.next;
                  }
                  temp.next = newNode;
              }
          }
          public void display() {
              Node temp = head;
              while (temp != null) {
                  System.out.print(temp.data + " ");
                  temp = temp.next;
              }
          }
          public static void main(String[] args) {
              LinkedList list = new LinkedList();
              list.add(1);
              list.add(2);
              list.add(3);
              list.display();
          }
      }
    

Node Structure:

Each node contains data and a reference to the next node.

Adding Elements:

Elements can be added to the end of the list by traversing to the last node and updating its next reference.

Displaying Elements:

Traverse the list from head to tail, printing each node's data.

Console Output:

1 2 3

logo of wikigalaxy

Newsletter

Subscribe to our newsletter for weekly updates and promotions.

Privacy Policy

 • 

Terms of Service

Copyright © WikiGalaxy 2025