Can you write a program in C to implement a stack data structure?
- User
Can you write a program in C to implement a stack data structure?
- Assistant
I can try! Keep in mind this code may not be totally up to date and may require modifications to suit your needs.
C - User
Looks great! I tried it and it runs fine, too. But I think you're right, a dynamically resizeable stack would be better. Can you show me how to do it with a linked list? Write it just like before, that was perfect, just using linked lists this time.
- Assistant
Sure, here's a simple implementation of a stack using a singly linked list in C. This version of a stack will be dynamically resizable.
#include <stdio.h> #include <stdlib.h>
typedef struct Node { int data; struct Node* next; } Node;
Node* createNode(int data) { Node* newNode = (Node*) malloc(sizeof(Node)); if (!newNode) { printf("Heap overflow\n"); exit(0); } newNode->data = data; newNode->next = NULL; return newNode; }
int isEmpty(Node* top) { return top == NULL; }
void push(Node** top, int data) { Node* newNode = createNode(data); newNode->next = *top; *top = newNode; }
int pop(Node** top) { Node* temp; int poppedValue; if (isEmpty(*top)) { printf("Stack underflow\n"); return -1; } temp = *top; poppedValue = temp->data; *top = temp->next; free(temp); return poppedValue; }
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →
- Human-written demonstration (OpenAssistant volunteers)Compare side by side →