C中泛型的栈的实现

C语言中没有泛型的类型,但是有(void *)指针。可以说(void *)指针就是C语言中的泛型。

在数据结构中有很多种数据结构相关算法的实现都需要用到栈。如表达式求值,迷宫求解,中序遍历二叉树的非递归算法,拓扑排序,关键路径等等,算法都需要用栈。所以,有时候需要用一个”泛型“数据结构。而不是用typedef或者需要的时候重新写一个数据结构。

代码如下:

#include 
#include 
#include 
#include 

typedef struct stack {
	void *elems;
	int elemSize;
	int length;
	int allocLength;
}stack;

void initStack(stack *s, int elemSize)
{
	s->length = 0;
	s->elemSize = elemSize;
	s->allocLength = 4;
	s->elems = malloc(4 * s->elemSize);
}
void stackDispose(stack *s)
{
	free(s->elems);
}
static void growStack(stack *s)
{
	s->allocLength *= 2;
	s->elems = realloc(s->elems, s->allocLength * s->elemSize);
}
static bool isEmpty(stack *s)
{
	if (s->length > 0)
		return false;
	else
		return true;
}
void stackPush(stack *s, void *elemAddr)
{
	if (s->allocLength == s->length)
		growStack(s);
	void *target = (char *)s->elems + s->elemSize * s->length; //为什么是用char *,而不是使用其他?这里使用其他类型也是可以的,因为最终都会被强制转换成void *类型。
	memcpy(target, elemAddr, s->elemSize);			   //讲elemAddr中的内存地址拷贝到target中去,即栈顶
	s->length++;
}
void stackPop(stack *s, void *elemAddr)
{
	if (isEmpty(s))
		return;
	s->length--;
	void *source = (char *)s->elems + s->elemSize * s->length;
	memcpy(elemAddr, source, s->elemSize);
}
/*
 *测试,利用字符串进行测试
 */

int main()
{
	stack s;
	char *str[] = {"hello","world", "are", "you" , "ok"};
	initStack(&s, sizeof(char *));
	for (int i = 0; i < 5; i++) {
		char *copy = _strdup(str[i]);	//_strdup这是标准C/C++中的函数,如果是在Unix's系列上,则是使用POSIX中的函数strdup
		stackPush(&s, ©);		//为什么是使用©而不是使用copy?
	}
	

	char *name;
	for (int i = 0; i < 5; i++)
	{
		stackPop(&s, &name);
		printf("%s %d \n", name, s.length);
	}
	stackDispose(&s);

    return 0;
}

你可能感兴趣的:(C中泛型的栈的实现)