#include <stdio.
h>
#include <stdlib.h>
// Node structure
struct Node {
int data;
struct Node* next;
};
// Top pointer (points to stack top)
struct Node* top = NULL;
// Function to push 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;
printf("%d pushed to stack\n", value);
}
// Function to check if stack is empty
int isEmpty() {
return top == NULL;
}
// Function to pop an element
int pop() {
if (isEmpty()) {
printf("Stack Underflow\n");
return -1;
}
struct Node* temp = top;
int popped = temp->data;
top = top->next;
free(temp);
return popped;
}
// Function to see top element
int peek() {
if (!isEmpty())
return top->data;
else
return -1;
}
// Function to display stack
void display() {
if (isEmpty()) {
printf("Stack is empty\n");
return;
}
struct Node* temp = top;
printf("Stack elements: ");
while (temp != NULL) {
printf("%d -> ", temp->data);
temp = temp->next;
}
printf("NULL\n");
}
// Main function
int main() {
push(10);
push(20);
push(30);
display();
printf("Top element is %d\n", peek());
printf("%d popped from stack\n", pop());
display();
return 0;
}
Implementation Stack using Array
#include <stdio.h>
#define MAX 5 // Maximum size of the stack
int stack[MAX];
int top = -1; // Initially stack is empty
// Function to check if stack is full
int isFull() {
return top == MAX - 1;
}
// Function to check if stack is empty
int isEmpty() {
return top == -1;
}
// Function to push an element
void push(int value) {
if (isFull()) {
printf("Stack Overflow! Cannot push %d\n", value);
} else {
stack[++top] = value;
printf("%d pushed to stack\n", value);
}
}
// Function to pop an element
int pop() {
if (isEmpty()) {
printf("Stack Underflow! Cannot pop\n");
return -1;
} else {
return stack[top--];
}
}
// Function to peek (top element)
int peek() {
if (isEmpty()) {
printf("Stack is empty!\n");
return -1;
} else {
return stack[top];
}
}
// Function to display stack
void display() {
if (isEmpty()) {
printf("Stack is empty!\n");
} else {
printf("Stack elements: ");
for (int i = top; i >= 0; i--) {
printf("%d ", stack[i]);
}
printf("\n");
}
}
// Main function
int main() {
push(10);
push(20);
push(30);
display();
printf("Top element: %d\n", peek());
printf("Popped element: %d\n", pop());
display();
return 0;
}