Last active
May 16, 2017 19:15
-
-
Save rjwebb/1994535134e70262db1d69d51ba18fc8 to your computer and use it in GitHub Desktop.
Stack / Linked List implementation.
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> | |
/** | |
Very simple stack / linked list data structure for | |
holding integers. | |
**/ | |
typedef struct Cell { | |
struct Cell* next; | |
int value; | |
} llCell; | |
typedef struct { | |
llCell* head; | |
} Stack; | |
void push(Stack* stack, int item) | |
{ | |
llCell* newCell; | |
newCell = malloc (sizeof (llCell)); | |
newCell->value = item; | |
newCell->next = stack->head; | |
// make the new cell the head of the stack | |
stack->head = newCell; | |
} | |
int pop(Stack* stack) | |
{ | |
if(stack->head == NULL) { | |
// stack is empty | |
return -1; | |
} else { | |
llCell* oldHead = stack->head; | |
stack->head = oldHead->next; | |
int output = oldHead->value; | |
free(oldHead); | |
return output; | |
} | |
} | |
Stack* allocate_stack() | |
{ | |
Stack* stack; | |
stack = (Stack*) malloc (sizeof (Stack)); | |
stack->head = NULL; | |
return stack; | |
} | |
int main(void) | |
{ | |
Stack* stack = allocate_stack(); | |
push(stack, 1); | |
push(stack, 2); | |
push(stack, 3); | |
push(stack, 4); | |
printf("%d\n", pop(stack)); // 4 | |
printf("%d\n", pop(stack)); // 3 | |
printf("%d\n", pop(stack)); // 2 | |
printf("%d\n", pop(stack)); // 1 | |
printf("%d\n", pop(stack)); // -1 | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment