c语言实现链式栈

#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
struct Linknode
{
	struct Linknode* next;
};
struct LStack
{
	struct Linknode pHeader;
	int m_size;
};
typedef void* linkstack;
初始化栈
linkstack init_linkstack()
{
	struct LStack* mystack = (struct LStack*)malloc(sizeof(struct LStack));
	if (mystack == NULL)
	{
		return NULL;
	}
	mystack->pHeader.next = NULL;
	mystack->m_size = 0;
	return mystack;
}
void push_linkstack(linkstack stack, void* data)
{
	if (stack == NULL)
	{
		return;
	}
	if (data == NULL)
	{
		return;
	}
	//本质头插
	struct LStack* mystack = (struct LStack*)stack;
	struct Linknode* mynode = (struct Linknode* )data;
	//建立关系
	mynode->next = mystack->pHeader.next;
	mystack->pHeader.next = mynode;
	mystack->m_size++;
}
//出栈
void pop_linkstack(linkstack stack)
{
	if (stack == NULL)
	{
		return;
	}
	struct LStack* mystack = (struct LStack*)stack;
	if (mystack->m_size == 0)
	{
		return;
	}
	//创建指向第一个节点的指针
	struct Linknode* pFirst = mystack->pHeader.next;
	//更新指向
	mystack->pHeader.next = pFirst->next;
	mystack->m_size--;

}
//返回栈顶
void* top_linkstack(linkstack stack)
{
	if (stack == NULL)
	{
		return NULL;
	}
	struct LStack* mystack = (struct LStack*)stack;
	if (mystack->m_size == 0)
	{
		return NULL;
	}
	return mystack->pHeader.next;
}
//返回栈大小
int size_linkstack(linkstack stack)
{
	if (stack == NULL)
	{
		return 0 ;
	}
	struct LStack* mystack = (struct LStack*)stack;
	return mystack->m_size;
}
//判断是否为空
int isEmpty_linkstack(linkstack stack)
{
	if (stack == NULL)
	{
		return -1;
	}
	struct LStack* mystack = (struct LStack*)stack;
	if (mystack->m_size == 0)
	{
		return 1;
	}
	return 0;
}
//销毁
void destroy_linkstack(linkstack stack)
{
	if (stack == NULL)
	{
		return ;
	}
	free(stack);
	stack = NULL;
}
struct person
{
	int* a;
	char name[64];
	int age;
};
void test01()
{
	linkstack mystack = init_linkstack();
		struct person p6 = {NULL, "aaa",18 };
	struct person p7 = { NULL, "bbb",123 };
	struct person p8 = { NULL ,"ccc",24 };
	struct person p9 = { NULL,"ddd",25 };
	//入栈
	push_linkstack(mystack, &p6);
	push_linkstack(mystack, &p7);
	push_linkstack(mystack, &p8);
	push_linkstack(mystack, &p9);
	printf("栈大小:%d\n", size_linkstack(mystack));
	while (!isEmpty_linkstack(mystack))//栈不为空,查看栈顶并出栈
	{
		struct person* p = (struct person*)top_linkstack(mystack);
		printf("栈顶元素-姓名:%s,年龄:%d\n", p->name, p->age);
		pop_linkstack(mystack);//出栈
	}
	printf("栈大小:%d\n", size_linkstack(mystack));

}
int main()
{
	test01();
	return 0;
}

你可能感兴趣的:(c语言,算法,开发语言)