Skip to content

Instantly share code, notes, and snippets.

@bweston92 bweston92/main.c
Created Sep 1, 2017

Embed
What would you like to do?
Stack example in C.
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
typedef struct stack_item
{
// The value given to the item.
int value;
// The pointer to the previous item.
struct stack_item * prev;
} stack_item;
typedef struct stack
{
// The current length of the stack.
int length;
// The head is a pointer to the value at the top of the stack.
stack_item * head;
} stack;
stack * create_stack()
{
stack * s = (stack *) malloc(sizeof(stack));
s->length = 0;
s->head = NULL;
return s;
}
void stack_push(stack * s, int value)
{
stack_item * si = (stack_item *) malloc(sizeof(stack_item));
si->value = value;
si->prev = s->head;
s->head = si;
s->length++;
}
int stack_pop(stack * s)
{
// Get the value from the current item before we remove it.
int value = s->head->value;
stack_item * i = s->head;
// Set head on the stack to the previous item.
s->head = s->head->prev;
// Decrement the size of the stack.
s->length--;
// Free up the memory allocated for the previous item.
free(i);
// Return the value we stored from the item we removed.
return value;
}
int main() {
stack * s = create_stack();
stack_push(s, 1);
stack_push(s, 2);
stack_push(s, 3);
printf("First: %d\n", stack_pop(s));
printf("Second: %d\n", stack_pop(s));
printf("Third: %d\n", stack_pop(s));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.