Yesterday, one of my Facebook friend asked me this question. My answer is "yes", and in this post I will discuss how could we do this.
I am a great supporter of working with unions and I will be using union for it.
If you are to implement the stack with arrays, then within the stack array you need to maintain a union so that you can store different data types. Along with this you need to have stack top variable and an array to keep track of data type of each array position.
Here is the code. I have written it in great hurry and therefore the code is not fully optimized..but it is running obviously.
#include
#include
#define CHARACTER 1
#define INTEGER 2
#define UNKNOWN 3
#define INVALID_INT -99
#define INVALID_CHAR '~'
union Data
{
int ival;
char cval;
};
struct STACK
{
union Data* arr;
int topVal;
int* topType;
};
struct POPVAL
{
int pival;
char pcval;
};
struct STACK* initStack(int size)
{
int i;
struct STACK* p;
p =(struct STACK*)malloc(sizeof(struct STACK));
p->arr = (union Data*)malloc (size*sizeof(union Data));
p->topVal = -1;
p->topType = (int *)malloc (size*sizeof(int));
for(i = 0; i<size; i++)
p->topType[i] = UNKNOWN;
printf("\n Stack is initialized...");
return p;
}
void pushChar(struct STACK* p, int size)
{
if(p->topVal == size - 1)
printf("\n Overflow Condition Appears.... No Push Posible....");
else
{
p->topVal = p->topVal + 1;
fflush(stdin);
printf("\n Enter the character to push:");
scanf("%c", &p->arr[p->topVal].cval);
p->topType[p->topVal] = CHARACTER;
printf("\n Character Push Done....");
}
}
void pushInt(struct STACK* p, int size)
{
if(p->topVal == size - 1)
printf("\n Overflow Condition Appears.... No Push Posible....");
else
{
p->topVal = p->topVal + 1;