>Daniel's Homepage

Posts

My posts about programming and things.
Date format is day/month/year because I'm sane.

Simple stack

4/2/2020

I'm exploring data structures and I find I learn best when I put something out, so first with a stack. This is my simple implementation using an array. A linked list would be better but that's more verbose.

/*
 * stack using array
 */
#include <stdio.h>
#include <stdlib.h>

struct stack
{
	ssize_t size;
	ssize_t top;
	int *array;
};

struct stack
*createstack(size_t size)
{
	struct stack *stack = malloc(sizeof(struct stack));
	stack->size = size;
	stack->top = -1;
	stack->array = malloc(sizeof(int) * stack->size);
	return stack;
}

void
destroystack(struct stack *stack)
{
	free(stack->array);
	free(stack);
}

int
isempty(struct stack *stack)
{
	return (stack->top == -1);
}

void
pushstack(struct stack *stack, int val)
{
	if (stack->top+1 > stack->size)
	{
		fprintf(stderr, "stack is full, can't push\n");
		return;
	}
	stack->top++;
	stack->array[stack->top] = val;
}

int
popstack(struct stack *stack)
{
	if (isempty(stack))
	{
		fprintf(stderr, "stack is empty, can't pop\n");
		/* in the real world we would not be holding ints so -1 will do */
		return -1;
	}
	int popped = stack->array[stack->top];
	stack->top--;
	return popped;
}

int
peekstack(struct stack *stack)
{
	if (isempty(stack))
	{
		fprintf(stderr, "stack is empty, can't peek\n");
		return -1;
	}
	return stack->array[stack->top];
}

void
printstack(struct stack *stack)
{
	if (isempty(stack))
	{
		fprintf(stderr, "stack is empty\n");
	}
	for (ssize_t i = 0; i <= stack->top; i++)
	 {
		printf("[%zd] = %d\n", i, stack->array[i]);
	 }
}

int
main(void)
{
	struct stack *stack = createstack(50);
	printf("isempty: %d\n", isempty(stack));
	pushstack(stack, 5);
	pushstack(stack, 10);
	pushstack(stack, 15);
	printf("peek: %d\n", peekstack(stack));
	printf("isempty: %d\n", isempty(stack));
	printstack(stack);
	puts("popstack()");
	printf("popped: %d\n", popstack(stack));
	printstack(stack);
	printf("popped: %d\n", popstack(stack));
	printstack(stack);
	printf("popped: %d\n", popstack(stack));
	printstack(stack);
	destroystack(stack);
	return 0;
}




RSS feed
FSF member

page generated 19/11/2024 using websitegenerator in C