C 顺序栈的基本操作

实现代码如下:

#include<iostream>
using namespace std;

const int maxSize = 100;

typedef struct{//主要是要有一个数组,和一个top,top空时可用-1代替 
	int data[maxSize];
	int top;
}SqStack;

void initStack(SqStack &st);
int isEmpty(SqStack st);
int Push(SqStack &st,int x);
int Pop(SqStack &st,int &x);

int main(){
	SqStack stack;
	initStack(stack);
	Push(stack,5);
	Push(stack,564);
	Push(stack,25);
	
	cout<<stack.data[stack.top]<<endl;	
	
	int x;
	Pop(stack,x);
	cout<<x<<endl;
	
	cout<<stack.data[stack.top]<<endl;	
	
	return 0;
}

void initStack(SqStack &st){
	st.top = -1;
}

int isEmpty(SqStack st){
	if(st.top == -1)
		return 1;
	else
		return 0;
}

int Push(SqStack &st,int x){
	if(st.top == maxSize-1)
		return 0;
	++(st.top); 
	st.data[st.top] = x;
	return 1;
}

int Pop(SqStack &st,int &x){
	if(st.top == -1)
		return 0;
	x = st.data[st.top];
	--(st.top);
	return 1; 
}

猜你喜欢

转载自blog.csdn.net/qq_29762941/article/details/81463558
今日推荐