Skip to content

Commit

Permalink
stack with c
Browse files Browse the repository at this point in the history
  • Loading branch information
sujan-poudel-03 committed May 6, 2023
1 parent f415cb0 commit 7d45586
Show file tree
Hide file tree
Showing 2 changed files with 88 additions and 0 deletions.
88 changes: 88 additions & 0 deletions C/stack/stack.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#include <stdio.h>

int MAXSIZE = 8;
int stack[8];
int top = -1;

/* Check if the stack is full */
int isFull() {
if (top == MAXSIZE)
return 1;
else
return 0;
}

/* Check if the stack is empty */
int isEmpty() {
if (top == -1)
return 1;
else
return 0;
}

/* Add elements into stack */
void push(int data) {
if (!isFull()) {
top = top + 1;
stack[top] = data;
} else {
printf("Could not insert data, Stack is full.\n");
}
}

/* Remove element from stack */
int pop() {
int data;

if (!isEmpty()) {
data = stack[top];
top = top - 1;
return data;
} else {
printf("Could not retrieve data, Stack is empty.\n");
}
}

/* Returns element at top of stack */
int peek() {
return stack[top];
}

/* Display the stack */
void display() {
int i;

if (!isEmpty()) {
for (i = top; i >= 0; i--)
printf("%d ", stack[i]);
printf("\n");
} else {
printf("Stack is empty.\n");
}
}

int main() {
// push items on to the stack
push(3);
push(5);
push(9);
push(1);
push(12);
push(15);

printf("Element at top of the stack: %d\n", peek());
printf("Elements: \n");

// print stack data
display();

// remove element from stack
printf("\nElement popped: %d\n", pop());
printf("Element at top of the stack: %d\n", peek());
printf("Elements: \n");

// print stack data
display();

return 0;
}
Binary file added C/stack/stack.exe
Binary file not shown.

0 comments on commit 7d45586

Please sign in to comment.