Difference Between Array and Linked List, Stack and Queue
Difference Between Array and Linked List:
| Feature | Array | Linked List
|--------------------|-----------------------------------------------------------------------|----------------------------------------
----------------------------|
| Definition | A collection of elements stored in contiguous memory locations. | A collection of
nodes, where each node contains data and a reference to the next node. |
| Access | Direct access using index. | Sequential access through
pointers. |
| Size | Fixed size defined at creation. | Dynamic size; can grow or
shrink during runtime. |
| Insertion/Deletion | Expensive; requires shifting elements. | Efficient; only
requires pointer adjustment. |
| Memory Usage | Memory is pre-allocated. | Uses additional
memory for pointers. |
Example:
- Array: int arr[5] = {1, 2, 3, 4, 5};
- Linked List:
struct Node {
int data;
struct Node* next;
};
Difference Between Stack and Queue:
| Feature | Stack | Queue |
|--------------------|--------------------------------------------|------------------------------------------|
| Definition | Linear data structure following LIFO (Last In, First Out). | Linear data structure
following FIFO (First In, First Out). |
| Operations | Push (add), Pop (remove), Peek (view top). | Enqueue (add), Dequeue (remove),
Peek (view front). |
| Access | Only the top element is accessible. | Both front and rear elements are
accessible. |
| Usage | Used in recursion, expression evaluation. | Used in scheduling, buffering. |
Examples:
- Stack:
#include <stdio.h>
#define MAX 5
int stack[MAX], top = -1;
void push(int value) { stack[++top] = value; }
int pop() { return stack[top--]; }
- Queue:
#include <stdio.h>
#define MAX 5
int queue[MAX], front = 0, rear = -1;
void enqueue(int value) { queue[++rear] = value; }
int dequeue() { return queue[front++]; }