Write a C program which implements a stack It should read co

•Write a C program which implements a stack. It should read commands from standard input lines with this format: cmdfill where cmd is PUSH or POP And where fill is present iff the cmd is PUSH “Fill” is an integer; •When the program encounters an EOF it should print all characters from the base of its stack to the top (and only those integers). •It should use scanf to read its input and use malloc() allocate memory in blocks of 64. •Consider using the string functions as well.

Solution

#include<stdio.h>

#include<stdlib.h>

typedef struct Stack

{

int fill;

int size;

int *elements;

}Stack;

Stack * createStack(int maxElements)

{

Stack *S;

S = (Stack *)malloc(sizeof(Stack));

S->elements = (int *)malloc(sizeof(int)*maxElements);

S->size = 0;

S->fill = maxElements;

  

return S;

}

void pop(Stack *S)

{

if(S->size==0)

{

printf(\"Stack is Empty\ \");

return;

}

else

{

S->size--;

}

return;

}

int top(Stack *S)

{

if(S->size==0)

{

printf(\"Stack is Empty\ \");

exit(0);

}

return S->elements[S->size-1];

}

void push(Stack *S,int element)

{

if(S->size == S->fill)

{

printf(\"Stack is Full\ \");

}

else

{

S->elements[S->size++] = element;

}

return;

}

int main()

{

Stack *S = createStack(5);

push(S,7);

push(S,5);

push(S,21);

push(S,-1);

printf(\"Top element is %d\ \",top(S));

pop(S);

printf(\"Top element is %d\ \",top(S));

pop(S);

printf(\"Top element is %d\ \",top(S));

pop(S);

printf(\"Top element is %d\ \",top(S));

}

•Write a C program which implements a stack. It should read commands from standard input lines with this format: cmdfill where cmd is PUSH or POP And where fill

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site