#include <stdio.h>
#include <stdlib.h>
// Define the structure of a stack node
struct Node {
int data;
struct Node* next;
};
// Function prototypes
void create(struct Node** top);
void push(struct Node** top, int val);
int pop(struct Node** top);
int stackTop(struct Node** top);
int main() {
struct Node* top = NULL; // Initialize the stack as empty
int choice, val;
printf("\n<<< DYNAMIC STACK IMPLEMENTATION >>>\n");
while (1) {
printf("\n\n<<<< MENU >>>>");
printf("\n1. Create Stack");
printf("\n2. Push");
printf("\n3. Pop");
printf("\n4. Stack Top");
printf("\n5. Exit");
printf("\nEnter your choice: ");
scanf("%d", &choice);
switch (choice) {
case 1:
create(&top);
printf("\nStack created successfully!");
break;
case 2:
printf("\nEnter a value to push: ");
scanf("%d", &val);
push(&top, val);
printf("\nValue pushed successfully!");
break;
case 3:
val = pop(&top);
if (val == -999)
printf("\nStack is empty!");
else
printf("\n%d popped successfully!", val);
break;
case 4:
val = stackTop(&top);
if (val == -999)
printf("\nStack is empty!");
else
printf("\nStack top is %d", val);
break;
case 5:
printf("\nExiting program.");
exit(0);
default:
printf("\nInvalid choice! Please try again.");
}
}
return 0;
}
// Function to create an empty stack
void create(struct Node** top) {
*top = NULL; // Initialize the stack top as NULL
}
The single pointer (*top) represents the pointer to the top of the stack.
The double pointer (**top) is used because we want to modify the original pointer (top) in the main function directly.
// Function to push an element onto the stack
void push(struct Node** top, int val) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (!newNode) {
printf("\nMemory allocation failed.");
return;
}
newNode->data = val;
//Assigns the value val to the data field of the new node
newNode->next = *top;
//Links the new node to the current top of the stack by pointing its next to the current top.
*top = newNode;
//Updates the top pointer to make the new node the top of the stack.
}
// Function to pop an element from the stack
int pop(struct Node** top) {
if (*top == NULL) {
return -999; // Return -999 if the stack is empty
}
struct Node* temp = *top;
//Store the current top node in temp for later removal.
int val = temp->data;
//Extract the data from the top node.
*top = (*top)->next;
//Move the top to the next node in the stack.
free(temp);
//Delete the old top node to release memory
return val;
}
// Function to get the top element of the stack
int stackTop(struct Node** top) {
if (*top == NULL) {
return -999; // Return -999 if the stack is empty
}
return (*top)->data;
//It accesses the data of the node pointed to by *top (the top node of the stack).
}