(数据结构)链栈的基本操作

#include
#include
//类型创建
typedef struct	LinkedStackNode
{
	int data;
	struct LinkedStackNode* next;
}LinkedStackNode, * LinkedStack;
LinkedStack top;
//链栈的初始化
//头结点的初始化
LinkedStack Init_LinkedStack()
{
	LinkedStack top = (LinkedStackNode*)malloc(sizeof(LinkedStackNode));
	if (top != NULL)
	{
		top->next = NULL;
	}
	else
	{
		printf("头结点申请空间失败\n");
	}
	return top;
}
//判断栈空
void LinkedStack_Empty(LinkedStack top)
{
	if (top->next == NULL)
	{
		printf("链栈为空\n");
	}
	else
	{
		printf("链栈不为空\n");
	}
}
//入栈
int Push_LinkedStack(LinkedStack top, int x)
{
	LinkedStackNode* node;
	node = (LinkedStackNode*)malloc(sizeof(LinkedStackNode));
	if (node == NULL)
	{
		printf("节点申请空间失败\n");
		return 0;
	}
	node->data = x;
	node->next = top->next;
	top->next = node;
	return 1;
}
//出栈
int Pop_LinkedStack(LinkedStack top, int* x)
{
	LinkedStackNode* node;
	if (top->next == NULL)
	{
		printf("链栈为空,无法进行出栈操作\n");
		return 0;
	}
	else
	{
		node = top->next;
		*x = node->data;
		top->next = node->next;  //将头结点后的节点整体向前一位
		free(node);
		return 1;
	}
}
//读取栈顶元素
int Get_LinkedStack(LinkedStack top, int* x)
{
	if (top->next == NULL)
	{
		printf("链栈为空\n");
		return 0;
	}
	else
	{
		*x = top->next->data;
		return 1;
	}
}
//n的阶乘
int JieCheng(int n)
{
	if (n == 1 || n == 0)
	{
		return 1;
	}
	else
	{
		return n * JieCheng(n - 1);
	}
	return 0;
}
int main()
{
	//栈的初始化
	//头结点的初始化
	LinkedStack top;
	top = Init_LinkedStack();
	if (top == NULL)
	{
		printf("申请链栈空间失败\n");
	}
	//入栈
	int x;
	printf("请输入需要入栈的值,输入9999停止输入\n");
	scanf("%d", &x);
	int count = 0;
	while (x != 9999)
	{
		Push_LinkedStack(top, x);
		count++;
		printf("请输入需要入栈的值,输入9999停止输入\n");
		scanf("%d", &x);
	}
	//出栈
	int y=0;
	while (count--)
	{
		Pop_LinkedStack(top, &y);
		printf("%d ", y);
	}
	return 0;
}

你可能感兴趣的:(数据结构,c语言,算法,数据结构)