Stack
A stack is a linear data structure that follows the Last In, First Out (LIFO) principle, where the last element added to the stack is the first one to be removed. It can be thought of as a collection of elements with two main operations: push, which adds an element to the top of the stack, and pop, which removes the top element from the stack.
Implementation
Stacks can be implemented using arrays or linked lists.
#define MAX_SIZE 100 // Maximum size of the stack
typedef struct {
int arr[MAX_SIZE];
int top; // Index of the top element
} Stack;
// Function to initialize a stack
void initializeStack(Stack *s) {
s->top = -1; // Empty stack
}
// Function to push an element onto the stack
void push(Stack *s, int value) {
if (s->top == MAX_SIZE - 1) {
printf("Stack Overflow!\n");
return;
}
s->arr[++s->top] = value;
}
// Function to pop an element from the stack
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack Underflow!\n");
return -1; // Returning a default value
}
return s->arr[s->top--];
}typedef struct Node {
int data;
struct Node* next;
} Node;
typedef struct {
Node* top; // Pointer to the top node
} Stack;
// Function to initialize a stack
void initializeStack(Stack *s) {
s->top = NULL; // Empty stack
}
// Function to push an element onto the stack
void push(Stack *s, int value) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (newNode == NULL) {
printf("Memory allocation failed!\n");
return;
}
newNode->data = value;
newNode->next = s->top;
s->top = newNode;
}
// Function to pop an element from the stack
int pop(Stack *s) {
if (s->top == NULL) {
printf("Stack Underflow!\n");
return -1; // Returning a default value
}
int data = s->top->data;
Node* temp = s->top;
s->top = s->top->next;
free(temp);
return data;
}Operations
Common operations performed on stacks include:
Advantages of Stacks
Disadvantages of Stacks
Applications of Stacks
Examples of Stack Usage