Skip to content

Commit ae842fb

Browse files
Merge pull request #267 from jabedzaman/main
feat: added stack code
2 parents f20b99c + 7b676f4 commit ae842fb

1 file changed

Lines changed: 70 additions & 0 deletions

File tree

C/data_structures/stack/stack.c

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// Stack implementation in C
2+
3+
#include <stdio.h>
4+
#include <stdlib.h>
5+
#include <limits.h>
6+
7+
#define MAX 1000
8+
int stack[MAX];
9+
10+
// Initialize top of stack
11+
int top = -1;
12+
13+
// Function to add an item to stack
14+
void push(int data) {
15+
if (top == MAX - 1) {
16+
printf("Stack Overflow\n");
17+
return;
18+
}
19+
stack[++top] = data;
20+
}
21+
22+
// Function to remove an item from stack
23+
int pop() {
24+
if (top == -1) {
25+
printf("Stack Underflow\n");
26+
return INT_MIN;
27+
}
28+
return stack[top--];
29+
}
30+
31+
// Function to return the top from stack without removing it
32+
int peek() {
33+
if (top == -1) {
34+
printf("Stack is empty\n");
35+
return INT_MIN;
36+
}
37+
return stack[top];
38+
}
39+
40+
// helper functions
41+
int isEmpty() { return top == -1; }
42+
int isFull() { return top == MAX - 1; }
43+
int size() { return top + 1; }
44+
45+
// Function to display stack elements
46+
void display() {
47+
if (top == -1) {
48+
printf("Stack is empty\n");
49+
return;
50+
}
51+
for (int i = top; i >= 0; i--) {
52+
printf("%d ", stack[i]);
53+
}
54+
printf("\n");
55+
}
56+
57+
/**
58+
* Main function to demonstrate stack operations
59+
*/
60+
int main() {
61+
push(10); // Push 10 onto the stack
62+
push(20); // Push 20 onto the stack
63+
push(30); // Push 30 onto the stack
64+
display(); // Display stack elements
65+
printf("Top element is %d\n", peek()); // Peek at the top element
66+
printf("Stack size is %d\n", size()); // Get the size of the stack
67+
printf("Popped element is %d\n", pop()); // Pop the top element
68+
display(); // Display stack elements after pop
69+
return 0;
70+
}

0 commit comments

Comments
 (0)