What is a Data Structure?

A data structure is a way of organizing, storing, and managing data so that it can be used efficiently. It provides a systematic way to access and modify data, making it easier to solve problems and build algorithms.

Common Types of Data Structures

Here are some widely used data structures:

1. Arrays

  • A collection of elements stored in contiguous memory locations.
  • Example: [1, 2, 3, 4]
// Example: Array in Java
int[] numbers = {1, 2, 3, 4};
for (int number : numbers) {
    System.out.println(number);
}

2. Linked Lists

  • A sequence of nodes where each node points to the next.
  • Example: 1 -> 2 -> 3 -> 4
// Example: Node class for Linked List in Java
class Node {
    int data;
    Node next;

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

3. Stacks

  • A Last In, First Out (LIFO) structure.
  • Example: Adding plates to a stack and removing the top plate first.
// Example: Stack in Java
import java.util.Stack;
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
System.out.println(stack.pop()); // Outputs 20

4. Queues

  • A First In, First Out (FIFO) structure.
  • Example: A line of people waiting for a bus.
// Example: Queue in Java
import java.util.LinkedList;
import java.util.Queue;
Queue<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
System.out.println(queue.poll()); // Outputs 1

5. Trees

  • A hierarchical structure with a root node and child nodes.
  • Example: Family tree or file directory.
// Example: Binary Tree Node in Java
class TreeNode {
    int data;
    TreeNode left, right;

    TreeNode(int data) {
        this.data = data;
        left = right = null;
    }
}

6. Graphs

  • A set of nodes (vertices) connected by edges.
  • Example: Social networks, where people are nodes and friendships are edges.
// Example: Graph using Adjacency List in Java
import java.util.*;
class Graph {
    private Map<Integer, List<Integer>> adjList = new HashMap<>();

    void addEdge(int u, int v) {
        adjList.putIfAbsent(u, new ArrayList<>());
        adjList.get(u).add(v);
    }
}

Why are Data Structures Important?

  • Efficiency: They optimize data access and modification.
  • Scalability: Help in handling large datasets.
  • Problem Solving: Provide a foundation for designing efficient algorithms.

Real-Life Example

Imagine organizing books in a library:

  • Array: Books are stored on a single shelf.
  • Stack: Books are piled one on top of the other.
  • Queue: Books are borrowed in the order they were requested.
  • Tree: Books are categorized by genre, author, and title.

Using the right data structure is key to solving problems effectively.