Estructura básica de datos - pila

//模拟栈的实现
#include<iostream>
using namespace std;
#define maxSize 100
typedef int type;
typedef struct Stack{
	type data[maxSize];
	int top;
}Stack;
//初始化栈 
void init(Stack &stack){
	stack.top=-1; 
} 
//判栈空
int isEmpty(Stack &stack){
	return stack.top==-1;
} 
//判栈满
int isFull(Stack &stack){
	return stack.top==maxSize;
} 
//返回栈大小
int size(Stack &stack){
	return stack.top+1;
} 

//进栈操作
int push(Stack &stack,int x){
	if(isFull(stack)) return -1;
	stack.data[stack.top++]=x;
	return -1;
} 
//返回栈顶元素
int top(Stack &stack){
	if(isEmpty(stack)) return -1;
	return stack.data[stack.top-1];
} 
//出栈操作
int pop(Stack &stack){
	
	if(isEmpty(stack)) return -1;
	return stack.data[--stack.top];
} 
//清空栈
void clear(Stack &stack){
	while(!isEmpty(stack))
	{
		pop(stack);
	}
	init(stack);
} 

int main(){
	Stack stack;
	init(stack);
	type x;
	cin>>x;
	while(x!=-1){
		push(stack,x);
		cin>>x;
	}
	cout<<isEmpty(stack)<<endl;
	cout<<isFull(stack)<<endl;
	cout<<top(stack)<<endl;
	cout<<size(stack)<<endl;
	cout<<stack.top<<"top"<<endl;
	while(!isEmpty(stack))
		cout<<pop(stack)<<" ";
	cout<<endl;
	
	clear(stack);
		while(!isEmpty(stack))
		cout<<pop(stack)<<" ";
	cout<<endl;
	return 0;
}

Supongo que te gusta

Origin blog.csdn.net/Unknow_if/article/details/117464974
Recomendado
Clasificación