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.
Here are some widely used data structures:
[1, 2, 3, 4]
// Example: Array in Java
int[] numbers = {1, 2, 3, 4};
for (int number : numbers) {
System.out.println(number);
}
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;
}
}
// 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
// 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
// Example: Binary Tree Node in Java
class TreeNode {
int data;
TreeNode left, right;
TreeNode(int data) {
this.data = data;
left = right = null;
}
}
// 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);
}
}
Imagine organizing books in a library:
Using the right data structure is key to solving problems effectively.