Created
September 1, 2017 20:34
-
-
Save bweston92/88c86a76a5531f1b7a37c0a6891e578f to your computer and use it in GitHub Desktop.
Stack example in C.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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