tty-solitaire/lib/stack.c

75 lines
1.3 KiB
C
Raw Normal View History

2010-04-04 00:44:59 +00:00
#include <malloc.h>
#include <stdbool.h>
#include "stack.h"
void allocate_stack(struct stack **stack) {
*stack = malloc(sizeof(**stack));
2010-04-04 00:44:59 +00:00
allocate_card(&((*stack)->card));
return;
}
void initialize_stack(struct stack *stack) {
stack->next = NULL;
2010-04-04 00:44:59 +00:00
return;
2010-04-04 00:44:59 +00:00
}
2010-04-07 00:59:21 +00:00
void delete_stack(struct stack *stack) {
delete_card(stack->card);
free(stack);
return;
}
2010-04-04 00:44:59 +00:00
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 {
allocate_stack(&new_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
/* FIXME: uglyness inside if statement */
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;
if (length(*stack) == 1) {
allocate_stack(stack);
initialize_stack(*stack);
} else {
*stack = (*stack)->next;
}
2010-04-04 07:15:43 +00:00
popped_entry->next = NULL;
2010-04-04 01:12:42 +00:00
}
return(popped_entry);
}