(数据结构)栈与递归—求一个数的阶乘

#define _CRT_SECURE_NO_WARNINGS
#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");
	}
    //n的阶乘
	int n;
	printf("请输入一个整数n\n");
	scanf("%d", &n);
	int m = n;
	printf("入栈的元素为:");
	while (n)
	{
		int ret = JieCheng(n);
		printf("%d ",ret);
		Push_LinkedStack(top, ret);
		n--;
	}
	printf("\n");
	int y = 0;
	printf("出栈的元素为:");
	while (m--)
	{
		Pop_LinkedStack(top, &y);
		printf("%d ", y);
	}
	return 0;
}

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