Complete the stack implementation using dynamic array (vector type) NO WARNINGS
ID: 3728248 • Letter: C
Question
Complete the stack implementation using dynamic array (vector type) NO WARNINGS #de fine CRT SECURE #include #include typedef enum status (FAILURE, SUCCESS Status; typedef enum boolean FALSE, TRUE Boolean; typedef struct vStack f int top: //this is equivalent to size int capacity; int *data; vec stack; //function prototypes vec stack* stack constructor (O: Status push (vec stack stack, int item); Status pop (vec stack* stack) void print (vec stack* stack) Boolean isEmpty (vec_stack stack); I/ will return 0 if False,1 if true void stack_destroy (vec stack* stack); int main(int argc, char** argv) vec stack* stack; return 0; //function definitions vec-stack- stack-constructor() malloc(sizeof (vec stack)); { (vec vec-stack* vStack stack* if (vStack NULL) return NULL vStack-top . -1; vStack->capacity =1; vStack->data (int*)malloc ( sizeof (int)" vStack->capacity) if (vStack->dataNULL) free (vstack); return NULL return vStack;
Explanation / Answer
Assumption : Capacity of stack does not change dynamically
#include <stdio.h>
#include<stdlib.h>
typedef enum status{FAILURE, SUCCESS}Status;
typedef enum boolean{FALSE,TRUE}Boolean;
typedef struct vstack{
int top;
int capacity;
int *data;
}vec_stack;
vec_stack* stack_constructor();
Status push(vec_stack* stack,int item);
Status pop(vec_stack* stack);
void print(vec_stack* stack);
Boolean isEmpty(vec_stack* stack);
void stack_desctroy(vec_stack** stack);
vec_stack* stack_constructor(){
vec_stack *stack=(vec_stack*)malloc(sizeof(vec_stack));
stack->top=-1;
stack->capacity=1;
stack->data=(int *)malloc(sizeof(int)*stack->capacity);
return stack;
}
Status pop(vec_stack* stack){
if(stack->capacity==0){
return FAILURE;
}
printf("%d ",stack->data[stack->capacity-1]);
stack->capacity=stack->capacity-1;
return SUCCESS;
}
void print(vec_stack* stack){
int num_of_elements=stack->capacity;
for(int i=0;i<num_of_elements;i++){
printf("%d ",stack->data[i]);
}
printf(" ");
}
Boolean isEmpty(vec_stack* stack){
if(stack->capacity<=0)
return TRUE;
else
return FALSE;
}
Status push(vec_stack* stack,int item){
if(stack->capacity==stack->top){
return FAILURE;
}
stack->top=stack->top+1;
stack->data[stack->top]=item;
return SUCCESS;
}
void stack_desctroy(vec_stack** stack){
free((*stack)->data);
free(*stack);
}
int main(int argc,int **argv) {
vec_stack *vstack=stack_constructor();
push(vstack,1);
print(vstack);
isEmpty(vstack);
pop(vstack);
isEmpty(vstack);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.