链栈的入栈、出栈算法

#include
#include

typedef struct LinkStack
{
     
	char data;
	struct LinkStack *next;
}LinkStack;

LinkStack *L;

int main()
{
     
	void PushStack(int x);
	char PopStack();
	int i;
	char x;
	L = (LinkStack *)malloc(sizeof(LinkStack));
	L->next = NULL;
	for(i=0; i<5; i++)
	{
     
		printf("请输入第%d个元素\n",i+1);
		x = getchar();
		getchar();
		PushStack(x);
	}
	printf("pop first 5 elements\n");
	for(i=0; i<5; i++)
		printf("The %d element is %c\n", i+1, PopStack());
	return 0;
}

void PushStack(char x)  //入栈
{
     
	LinkStack *top;
	top = (LinkStack *)malloc(sizeof(LinkStack));
	top->data = x;
	top->next = L;
	L = top;
}

char PopStack()  //出栈
{
     
	char x;
	if(L->next == NULL)  //栈底
	{
     
		printf("空栈\n");
		exit(1);
	}
	else
	{
     
		LinkStack *top;
		x = L->data;
		top = L;
		L = top->next;
		free(top);
		return x;
	}
}

程序运行结果
链栈的入栈、出栈算法_第1张图片
如果感觉不错,那就给我点个赞吧(ノ ̄▽ ̄)

你可能感兴趣的:(数据结构与算法,C语言描述,链栈,数据结构与算法,C语言)