-
-
Save kgabis/1217227 to your computer and use it in GitHub Desktop.
Linked stack in C
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
#include "stack.h" | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <stdbool.h> | |
#include <assert.h> | |
void stackpush(Stack ** stack, int value) | |
{ | |
assert(stack != NULL); | |
if (*stack == NULL) | |
{ | |
*stack = (Stack *)malloc(sizeof(Stack)); | |
assert(*stack != NULL); /* TODO : allocation handling! */ | |
(*stack)->value = value; | |
(*stack)->lower = NULL; | |
return; | |
} | |
else | |
{ | |
Stack *new_node = (Stack *)malloc(sizeof(Stack)); | |
assert(new_node != NULL); /* TODO : allocation handling! */ | |
new_node->lower = *stack; | |
new_node->value = value; | |
*stack = new_node; | |
return; | |
} | |
} | |
int stackpop(Stack ** stack) | |
{ | |
assert(stack != NULL); /* here it might be wise to do NULL handling */ | |
Stack *new_top = (*stack)->lower; | |
int removed_value = (*stack)->value; | |
free(*stack); | |
*stack = new_top; | |
return removed_value; | |
} | |
void stackdispose(Stack * stack) | |
{ | |
while(stack != NULL) | |
stackpop(&stack); | |
} |
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
typedef struct node_t | |
{ | |
int value; | |
struct node_t * lower; | |
} Node; | |
typedef struct node_t Stack; | |
void stackpush(Stack**, int); | |
int stackpop(Stack**); | |
void stackdispose(Stack*); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment