数据结构复盘——链栈

#include 
#include 

typedef struct SNode *PtrToSNode;

//定义
struct SNode{
	int data;
	PtrToSNode next;
};
typedef PtrToSNode Stack;

//初始化
Stack CreateStack(){
	Stack S=(Stack)malloc(sizeof(struct SNode));
	S->next=NULL;
	return S;
}

//判空
bool IsEmpty(Stack S){
	return (S->next==NULL);
}

//入栈
bool push(Stack S,int x){
	Stack temp=(Stack)malloc(sizeof(struct SNode));
	temp->data=x;
	temp->next=S->next;
	S->next=temp;
	return true;
}

//出栈
int pop(Stack S){
	Stack First;
	int elem;

	if(IsEmpty(S)){
		printf("空!");
		return -1;
	}else{
		First=S->next;
		elem=First->data;
		S->next=First->next;
		free(First);
		return elem;
	}
}

//主函数
void main(){
	Stack S=CreateStack();
	int n,x,p;

	printf("请输入数据个数:");
	scanf("%d",&n);
	for(int i=0;i<n;i++){
		scanf("%d",&x);
		push(S,x);
	}

	while(!IsEmpty(S)){
		p=pop(S);
		printf("%d ",p);
	}
	printf("\n");
}

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