数据结构-顺序栈(使用静态数组)代码(王道自写笔记)

/*使用静态数组定义顺序栈*/
#include<stdio.h>
#define MaxSize 10    //此静态数组的最大值即顺序栈最多可存放的数据个数 
typedef struct
{
	int data[MaxSize];
	int top;
}SqStack;
void InitStack(SqStack &s);  //初始化栈
bool StackEmpty(SqStack s);  //判断栈空 
bool Push(SqStack &s,int x);   //入栈操作 
bool Pop(SqStack &s,int &x);    //出栈 
bool GetTop(SqStack s,int &x); //读栈顶元素 

void InitStack(SqStack &s)
{ 
	s.top=-1;        //初始化栈顶指针 
	return; 
 } 
 
bool StackEmpty(SqStack s)
{
 	if(s.top==-1)  
 	{
 		return true;
	 }
	 else
	 {
	 	return false;
	 }
}

//新元素入栈 
bool Push(SqStack &s,int x)
{
	if(s.top==MaxSize-1)     //判断栈是否满,若栈满则不能成功插入元素,返回错误 
	{
		return false;
	}
	s.top=s.top+1;
	s.data[s.top]=x;
	return true;
} 
//出栈操作
bool Pop(SqStack &s,int &x)
{
	if(s.top==-1)     //若栈空则没有元素可删除,返回错误 
	{
		return false;
	}
	while(s.top!=-1)
	{
		x=s.data[s.top];
	    s.top=s.top-1;
	    printf("%d   ",x);
	}
	printf("\n");
	
	return true;
 } 


//读栈顶元素 
bool GetTop(SqStack s,int &x)
{
	if(s.top==-1)
	{
		return false;
	 } 
	 x=s.data[s.top];
	 printf("栈顶元素为:%d\n",x);
	 return true;
 } 
 
int main(void)
{
	SqStack s;
	int x=0;
	InitStack(s);
	if(Push(s,3));//入栈操作 
	{
		printf("入栈成功!\n"); 
	}  
	Push(s,3);
	Push(s,4);
	Push(s,5);
	Push(s,6);
	GetTop(s,x); //读栈顶元素 
	printf("栈内元素出栈:");
    Pop(s,x);    //出栈 
	return 0;
 } 

 此栈的示意图

另一种栈的表示方式

#include<stdio.h>
#define MaxSize 10
typedef struct
{
	int data[MaxSize];
	int top;
}SqStack;

bool StackEmpty(SqStack s);
void InitStack(SqStack &s);
bool Push(SqStack &s,int x);   //入栈操作 
bool Pop(SqStack &s,int &x);    //出栈 
bool GetTop(SqStack s,int &x); //读栈顶元素 


bool StackEmpty(SqStack s)
{
	if(s.top==0)
	{
		return true;
	}
	else 
	{
		return false;
	}
}


void InitStack(SqStack &s)
{
	s.top==0;
	return;
}


//新元素入栈 
bool Push(SqStack &s,int x)
{
	if(s.top==MaxSize)     //判断栈是否满,若栈满则不能成功插入元素,返回错误 
	{
		return false;
	}
	s.data[s.top]=x;
	s.top=s.top+1;
	return true;
} 
//出栈操作
bool Pop(SqStack &s,int &x)
{
	if(s.top==0)     //若栈空则没有元素可删除,返回错误 
	{
		return false;
	}
	while(s.top!=0)
	{
	    s.top=s.top-1;
		x=s.data[s.top];
	    printf("%d   ",x);
	}
	printf("\n");
	
	return true;
 } 


//读栈顶元素 
bool GetTop(SqStack s,int &x)
{
	if(s.top==0)
	{
		return false;
	 } 
	 x=s.data[s.top-1];
	 printf("栈顶元素为:%d\n",x);
	 return true;
 } 
 

int main(void)
{
	SqStack s;
	int x=0;
	InitStack(s);
	if(Push(s,3));//入栈操作 
	{
		printf("入栈成功!\n"); 
	}  
	Push(s,3);
	Push(s,4);
	Push(s,5);
	Push(s,6);
	GetTop(s,x); //读栈顶元素 
	printf("栈内元素出栈:");
    Pop(s,x);    //出栈 
	return 0;
 } 

此栈示意图

两种栈的表示方式的区别在于一开始空栈时栈顶指针的指向,方式一的栈顶指针在空栈时指向栈底的下一个,方式二的栈顶指针在空栈时指向栈底。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值