Data structures fall into two broad categories: linear and nonlinear. Linear structures include arrays, linked lists, stacks, and queues; nonlinear ones encompass trees, heaps, hash tables, and graphs.
Array
An array stores elements of identical type in contiguous memory locations, with a fixed length once allocated.
Method 1 – Fixed-size declaration with element assignment:
int nums[5];
nums[0] = 10;
nums[1] = 20;
nums[2] = 30;
nums[3] = 40;
nums[4] = 50;
Method 2 – Direct aggregate initialization:
int nums[] = {10, 20, 30, 40, 50};
Method 3 – Resizable container using std::vector:
#include <vector>
std::vector<int> nums;
nums.emplace_back(10);
nums.emplace_back(20);
nums.emplace_back(30);
nums.emplace_back(40);
nums.emplace_back(50);
Linked List
A linked list consists of nodes scattered across memory, each holding data and a reference to the next node.
Node definition:
struct Node {
int data;
Node* link;
Node(int value) : data(value), link(nullptr) {}
};
Creating a chain of nodes:
Node* first = new Node(100);
Node* second = new Node(200);
Node* third = new Node(300);
first->link = second;
second->link = third;
Stack
A stack follows last-in-first-out (LIFO) semantics and can be implemented via arrays or linked lists.
Using STL stack:
#include <stack>
std::stack<int> st;
Operations illustrating LIFO behavior:
st.push(7);
st.push(14);
st.pop(); // removes 14
st.pop(); // removes 7
Queue
A queue adheres to first-in-first-out (FIFO) ordering, commonly realized with a linked list.
STL queue usage:
#include <queue>
std::queue<int> q;
Demonstrating FIFO mechanics:
q.push(7);
q.push(14);
q.pop(); // removes 7
q.pop(); // removes 14