tty-solitaire/lib/stack.c

60 lines
1.0 KiB
C
Raw Normal View History

2010-04-04 00:44:59 +00:00
#include <malloc.h>
#include <stdbool.h>
#include "card.h"
#include "stack.h"
struct stack *initialize_stack() {
struct stack *stack = NULL;
2010-04-04 07:15:43 +00:00
stack = malloc(sizeof(*stack));
2010-04-04 00:44:59 +00:00
stack->card = NULL;
stack->next = NULL;
return(stack);
}
bool empty(struct stack *stack) {
return(stack->card == NULL);
}
int length(struct stack *stack) {
2010-04-04 03:51:14 +00:00
struct stack *iterator = stack;
2010-04-04 00:44:59 +00:00
int length = 0;
if (!empty(stack)) {
length = 1;
2010-04-04 03:51:14 +00:00
while (iterator->next != NULL) {
2010-04-04 00:44:59 +00:00
length++;
2010-04-04 03:51:14 +00:00
iterator = iterator->next;
2010-04-04 00:44:59 +00:00
}
}
return(length);
}
2010-04-04 06:20:56 +00:00
void push(struct stack **stack, struct card *card) {
2010-04-04 00:44:59 +00:00
struct stack *new_stack = NULL;
2010-04-04 06:20:56 +00:00
if (empty(*stack)) {
(*stack)->card = card;
2010-04-04 00:44:59 +00:00
} else {
2010-04-04 06:20:56 +00:00
new_stack = initialize_stack();
2010-04-04 00:44:59 +00:00
new_stack->card = card;
2010-04-04 06:20:56 +00:00
new_stack->next = (*stack);
*stack = new_stack;
2010-04-04 00:44:59 +00:00
}
}
2010-04-04 01:12:42 +00:00
2010-04-04 07:15:43 +00:00
struct stack *pop(struct stack **stack) {
2010-04-04 01:12:42 +00:00
struct stack *popped_entry = NULL;
2010-04-04 07:15:43 +00:00
if(!empty(*stack)) {
popped_entry = *stack;
*stack = (*stack)->next;
popped_entry->next = NULL;
2010-04-04 01:12:42 +00:00
}
return(popped_entry);
}