Skip to content

Instantly share code, notes, and snippets.

@devil-cyber
Last active October 5, 2021 17:30
Show Gist options
  • Save devil-cyber/46644fc0b5d8170fbf4812e845090519 to your computer and use it in GitHub Desktop.
Save devil-cyber/46644fc0b5d8170fbf4812e845090519 to your computer and use it in GitHub Desktop.
Stack implementation in C
#include<stdio.h>
#include<stdlib.h>
#define INT_MIN -99999999
struct stack{
int top;
unsigned int capacity;
int * arr;
};
struct stack *createStack(unsigned int capacity){
struct stack *stack = (struct stack*)malloc(sizeof(struct stack));
stack->capacity = capacity;
stack->top = -1;
stack->arr = (int*)malloc(capacity*sizeof(int));
return stack;
}
int isFull(struct stack *s){
return s->top == s->capacity-1;
}
int isEmpty(struct stack *s){
return s->top==-1;
}
void push(struct stack *s, int data){
if(isFull(s))
return;
s->arr[++s->top] = data;
printf("The item %d pushed to stack\n", data);
}
int pop(struct stack *s){
if(isEmpty(s))
return INT_MIN;
return s->arr[s->top--];
}
int peek(struct stack *s){
if(isEmpty(s))
return INT_MIN;
return s->arr[s->top];
}
int main()
{
int capacity = 100;
struct stack *s = createStack(capacity);
push(s, 10);
push(s, 20);
push(s, 30);
printf("The peek of stack: %d\n", peek(s));
pop(s);
printf("The peek of stack: %d\n", peek(s));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment