数据结构——链栈的简单实现

//链栈的实现
#include
#include
typedef struct LinkStackNode{
	int data;
	LinkStackNode *top;
}LinkStackNode,*LinkStack;

//链栈的初始化
LinkStack InitLinkStack(LinkStack &LS){
	LS->top = NULL;
	return LS;
}

//判栈空
bool LinkStackEmpty(LinkStack &LS){
	if(LS->top == NULL)
		return true;
	else
		return false;
}

//入栈操作
bool Push(LinkStack &LS,int x){
	LinkStack q = (LinkStack)malloc(sizeof(LinkStackNode));
	q->data = x;
	q->top = LS->top;
	LS->top = q;
} 

//输出栈内元素
bool Stack_Print(LinkStack &LS){
	LinkStack p = LS->top;
	if(LinkStackEmpty(p)){
		printf("该栈为空栈!\n");
		return false;
	}
	else
		while(p!=NULL){
			printf("%d\n",p->data);
			p = p->top;
		}
} 

//出栈操作
int Pop(LinkStack &LS){
	int x;
	LinkStack p = LS->top;
	if(LinkStackEmpty(p)){
		printf("该栈为空栈!\n");
		return -1;
	}
	else{
		x= p->data;
		LS->top = p->top;
		free(p);
		p = p->top;
	}
	return x;
}

int main(){
	int x,counter,result;
	LinkStack L = (LinkStack)malloc(sizeof(LinkStack));
	InitLinkStack(L);
	printf("请输入入栈元素个数\n");
	scanf("%d",&counter);
	printf("请依次输入入栈元素:\n");
	for(int i = 0;i < counter;i++){
		scanf("%d",&x);
		Push(L,x);
	}
	printf("栈内元素如下所示:\n");
	Stack_Print(L);
	result = Pop(L);
	printf("出栈元素是:%d\n",result);
	printf("出栈结果如下所示:\n");
	Stack_Print(L);
	return 0;
} 

 

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