What Is Stack Data Structure in C?

A **stack** is a linear data structure in C that follows the Last-In-First-Out (LIFO) principle. It can be visualized as a stack of plates where the last plate added is the first one to be removed. In other words, the item that is inserted last is the first one to be removed from the stack.

## Basic Operations on a Stack

A stack supports three fundamental operations:

**Push**: This operation adds an element to the top of the stack.**Pop**: This operation removes the topmost element from the stack.**Peek**: Also known as__Top__, this operation returns the value of the topmost element without removing it from the stack.

## Implementation of Stack using an Array in C

In C, a stack can be implemented using an array. Here’s an example:

```
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
void push(int item) {
if (top >= MAX_SIZE - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = item;
}
int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}
int peek() {
if (top == -1) {
printf("Stack is empty\n");
return -1;
}
return stack[top];
}
int main() {
push(10);
push(20);
push(30);
printf("Top element: %d\n", peek());
printf("Popped element: %d\n", pop());
printf("Popped element: %d\n", pop());
return 0;
}
```

The above code demonstrates a stack implementation using an array. The **push()** function is used to insert elements into the stack, the **pop()** function removes elements from the stack, and the **peek()** function returns the value of the topmost element without removing it.

### Time Complexity of Stack Operations

The time complexity for all stack operations (push, pop, and peek) is O(1), which means they have constant time complexity regardless of the number of elements in the stack. This efficiency makes stacks suitable for many applications, including expression evaluation, function call management, and undo-redo mechanisms.

### Stack Applications

Some common applications of stacks include:

__Expression Evaluation__: Stacks are used to evaluate arithmetic expressions by converting them from infix notation to postfix or prefix notation.__Balanced Parentheses__: Stacks are employed to check whether parentheses in an expression are balanced or not.__Function Call Management__: Stacks are used to manage function calls and their local variables in programming languages.__Backtracking__: Stacks are utilized in backtracking algorithms like depth-first search (DFS).__Memoization__: Stacks can be used to store computed values for optimizing recursive algorithms.

Understanding the stack data structure is vital for mastering various algorithms and data structures. By using stacks effectively, you can solve complex problems efficiently.