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
Here is an implementation of a stack using a linked list in C:
js#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; struct Node* top = NULL; void push(int x) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = x; newNode->next = top; top = newNode; } void pop() { if(top == NULL) { printf("Stack Underflow\n"); return; } struct Node* temp = top; top = top->next; free(temp); } int peek() { if(top == NULL) { printf("Stack is empty\n"); return -1; } return top->data; } int main() { push(1); push(2); push(3); printf("Element at top of the stack: %d\n",peek()); pop(); printf("Element at top of the stack: %d\n",peek()); return 0; }In this implementation, each node contains the data and a pointer to the next node. push() allocates a new node, sets its data, and makes it point to the previous top. pop() frees the node pointed to by top and moves top to the next node. peek() simply returns the data of the node pointed to by top.
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 →