int isEmpty(Stack *stack) {
return stack->top == -1;
}
User
Can you write a version that supports types other than int? I want to put whatever type I want there
Assistant
Of course! Here's an improved and more readable version of the C program that implements a stack data structure supporting any data type using void pointers:
c
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This program defines a stack using a structure called Stack, which contains an array arr to store the elements and a variable top to keep track of the top element. The functions initialize, isEmpty, isFull, push, pop, and peek are implemented to perform various operations on the stack.
In the main function, the stack is initialized, elements are pushed onto the stack using the push function, and then popped using the pop function. The peek function is used to retrieve the top element without removing it. Finally, the program displays the top element of the stack.
Please note that this is a basic implementation of a stack and does not include error handling for all possible scenarios. You can enhance the program further based on your requirements.
#include <stdio.h>
#include <stdbool.h>
#define MAX_SIZE 100
typedef struct {
void *arr[MAX_SIZE];
int top;
} Stack;
void initialize(Stack *stack) {
stack->top = -1;
}
bool isEmpty(Stack *stack) {
return stack->top == -1;
}
bool isFull(Stack *stack) {
return stack->top == MAX_SIZE - 1;
}
void push(Stack *stack, void *data) {
if (isFull(stack)) {
printf("Stack Overflow: Cannot push element, stack is full.\n");
} else {
stack->arr[++stack->top] = data;
}
}
void* pop(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack Underflow: Cannot pop element, stack is empty.\n");
return NULL; // Return NULL indicating failure
} else {
return stack->arr[stack->top--];
}
}
void* peek(Stack *stack) {
if (isEmpty(stack)) {
printf("Stack is empty.\n");
return NULL; // Return NULL indicating failure
} else {
return stack->arr[stack->top];
}
}
int main() {
Stack stack;
initialize(&stack);
int num1 = 10;
int num2 = 20;
double pi = 3.14159;
char letter = 'A';
push(&stack, &num1);
push(&stack, &num2);
push(&stack, &pi);
push(&stack, &letter);
printf("Top element (char): %c\n", *(char*)peek(&stack));
printf("Top element (double): %lf\n", *(double*)peek(&stack));
printf("Popped element (double): %lf\n", *(double*)pop(&stack));
printf("Popped element (int): %d\n", *(int*)pop(&stack));
printf("Top element (int): %d\n", *(int*)peek(&stack));
return 0;
}
This version of the program uses void pointers (void*) to allow pushing and popping elements of any data type onto the stack. The main function demonstrates the usage of different data types (int, double, char) in the stack. Remember that you need to cast the pointers back to the appropriate data type when peeking and popping elements from the stack.