Skip to content

Instantly share code, notes, and snippets.

@Taaji
Created December 22, 2016 18:45
Show Gist options
  • Save Taaji/09c9291b7020c43f55506e7871e04c99 to your computer and use it in GitHub Desktop.
Save Taaji/09c9291b7020c43f55506e7871e04c99 to your computer and use it in GitHub Desktop.
//specialStack.h
typedef int stackElement;
typedef struct{
int top;
int maxSize;
stackElement *contents; //this is our array holding our stack elements
int min;
int nextmin;
}stackT;
stackT* stackInit(int maxsize);
void stackPush(stackT* newStack, stackElement element);
int stackPop(stackT *newStack);
int getMin(stackT *newStack);
int peek(stackT *newStack);
int stackIsFull(stackT *newStack);
int stackIsEmpty(stackT *newStack);
//specialStack.c
#include<stdlib.h>
#include<stdio.h>
#include<limits.h>
#include "specialStack.h"
stackT* stackInit(int maxSize){
stackT *newStack = (stackT *)malloc(sizeof(stackT));
newStack->contents = (stackElement *)malloc(sizeof(stackElement) * maxSize);
newStack->top = -1;
newStack->maxSize = maxSize;
newStack->min = INT_MAX;
newStack->nextmin = INT_MAX;
return newStack;
}
void stackPush(stackT *newStack, stackElement element){
if(stackIsFull(newStack)){
fprintf(stderr, "Stack is full! Can't push.\n");
exit(1);
}
if(element < newStack->min){
newStack->nextmin = newStack->min;
newStack->min = element;
}
newStack->contents[++newStack->top] = element;
printf("Pushed %d on the stack\n", element);
}
int stackPop(stackT *newStack){
if(stackIsEmpty(newStack)){
fprintf(stderr, "Stack is empty! Can't pop.\n");
exit(1);
}
if(newStack->contents[newStack->top] == newStack->min)
newStack->min = newStack->nextmin;
return newStack->contents[newStack->top--];
}
int getMin(stackT *newStack){
return newStack->min;
}
int peek(stackT *newStack){
return newStack->contents[newStack->top];
}
int stackIsEmpty(stackT *newStack){
return newStack->top == -1;
}
int stackIsFull(stackT *newStack){
return newStack->top == newStack->maxSize-1;
}
int main(){
stackT *newStack = stackInit(4);
stackPush(newStack, 10);
stackPush(newStack, 10);
stackPush(newStack, 30);
printf("Min element is: %d\n",getMin(newStack));
stackPush(newStack, 5);
printf("\nMin element is: %d\n",getMin(newStack));
return 0;
}
//Makefile
CC = gcc
CFLAGS = -Wall
specialStack: specialStack.o
$(CC) $(CFLAGS) -o specialStack specialStack.o
specialStack.o: specialStack.c specialStack.h
$(CC) $(CFLAGS) -c specialStack.c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment