Friday, March 10, 2023

Push & Pop, Array and Linked Implementation of Stack in C

 

1️⃣ Stack Using Array in C

An array-based stack uses a fixed-size array to store elements, and a top variable to track the topmost element.

📌 Structure of Stack using Array


#include <stdio.h> #define MAX 100 // Maximum stack size int stack[MAX]; // Array to store stack elements int top = -1; // Stack is empty initially // Push operation (Insert an element) void push(int value) { if (top == MAX - 1) { printf("Stack Overflow\n"); return; } stack[++top] = value; } // Pop operation (Remove an element) int pop() { if (top == -1) { printf("Stack Underflow\n"); return -1; } return stack[top--]; } // Display Stack Elements void display() { if (top == -1) { printf("Stack is empty\n"); return; } printf("Stack elements: "); for (int i = top; i >= 0; i--) printf("%d ", stack[i]); printf("\n"); } int main() { push(10); push(20); push(30); display(); printf("Popped: %d\n", pop()); display(); return 0; }

🔹 Time Complexity:

  • Push: O(1)
  • Pop: O(1)
  • Display: O(n)

2️⃣ Stack Using Linked List in C

A linked list-based stack dynamically allocates memory, so there's no size limitation. Each node contains a data value and a pointer to the next node.

📌 Structure of Stack using Linked List


#include <stdio.h> #include <stdlib.h> // Node structure struct Node { int data; struct Node* next; }; // Top pointer to track stack top struct Node* top = NULL; // Push operation (Insert an element) void push(int value) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); if (!newNode) { printf("Heap Overflow\n"); return; } newNode->data = value; newNode->next = top; top = newNode; } // Pop operation (Remove an element) int pop() { if (top == NULL) { printf("Stack Underflow\n"); return -1; } int value = top->data; struct Node* temp = top; top = top->next; free(temp); return value; } // Display Stack Elements void display() { if (top == NULL) { printf("Stack is empty\n"); return; } struct Node* temp = top; printf("Stack elements: "); while (temp) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); } int main() { push(10); push(20); push(30); display(); printf("Popped: %d\n", pop()); display(); return 0; }

🔹 Time Complexity:

  • Push: O(1)
  • Pop: O(1)
  • Display: O(n)

3️⃣ Key Differences: Array vs. Linked List Stack

FeatureStack Using ArrayStack Using Linked List
SizeFixed, pre-definedDynamic, no limit
Memory UsageUses contiguous memoryUses extra memory for pointers
Insertion/DeletionO(1) but size limitedO(1) and dynamic
Overflow RiskYes (if array is full)No (unless heap is full)
Underflow RiskYes (if stack is empty)Yes (if stack is empty)

No comments:

Post a Comment

Complete Binary Tree in Data Structures

  Complete Binary Tree in Data Structures 🌳 A Complete Binary Tree (CBT) is a type of Binary Tree where: ✔ All levels except possibly t...