-
-
Save ibeauregard/a5e21a872e07fdaa5696e644f9605578 to your computer and use it in GitHub Desktop.
Checkpoint at the end of part 1
This file contains 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
/* int_stack.h */ | |
#include <stdbool.h> | |
typedef struct int_stack IntStack; | |
IntStack* new_stack(); | |
void push_to_stack(IntStack* stack, int value); | |
int pop_stack(IntStack* stack); | |
int peek_stack(IntStack* stack); | |
bool is_empty_stack(IntStack* stack); | |
void delete_stack(IntStack** stack); | |
/* main.c */ | |
#include "int_stack.h" | |
#include <stdio.h> | |
int main() | |
{ | |
IntStack* stack = new_stack(); | |
for (int i = 5; i > 0; i--) { | |
push_to_stack(stack, i); | |
} | |
printf("At the top of the stack is `%d`\n\n", peek_stack(stack)); | |
while (!is_empty_stack(stack)) { | |
printf("`%d` was popped from the stack\n", pop_stack(stack)); | |
} | |
delete_stack(&stack); | |
return 0; | |
} | |
/* int_stack.c */ | |
#include "int_stack.h" | |
#include <stdlib.h> | |
typedef struct int_node IntNode; | |
struct int_stack { | |
IntNode* top; | |
}; | |
IntStack* new_stack() | |
{ | |
IntStack* stack = malloc(sizeof (IntStack)); | |
stack->top = NULL; | |
return stack; | |
} | |
struct int_node { | |
int value; | |
struct int_node* next; | |
}; | |
void push_to_stack(IntStack* stack, int value) | |
{ | |
IntNode* pushed = malloc(sizeof (IntNode)); | |
pushed->value = value; | |
pushed->next = stack->top; | |
stack->top = pushed; | |
} | |
int pop_stack(IntStack* stack) | |
{ | |
IntNode* new_top = stack->top->next; | |
int popped = stack->top->value; | |
free(stack->top); | |
stack->top = new_top; | |
return popped; | |
} | |
int peek_stack(IntStack* stack) | |
{ | |
return stack->top->value; | |
} | |
bool is_empty_stack(IntStack* stack) | |
{ | |
return !stack->top; | |
} | |
void delete_stack(IntStack** stack) | |
{ | |
while (!is_empty_stack(*stack)) { | |
pop_stack(*stack); | |
} | |
free(*stack); *stack = NULL; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment