c++使用动态内存构建的数组顺序栈

栈是一种先进后出的结构
可利用数组来构造一个顺序栈

首先定义栈的结构
包含三个部分 :
top值用于指示栈顶元素的上一个内存单位
用来存放栈值的数组
指向栈结构的指针

最先开始编写的代码遇到的问题:
初始定义函数的参数没有用指针,导致在主函数内的相关值并未改变。即在initstack调用后,cout<<a.top不为0,而为一个任意值。
犯了一个经典错误:全局变量的值在局部函数内无法改变。

struct stack{
	elementtype top;
	elementtype st[stacksize];
	stack *p;
};
void initstack(stack a){
	a.p=new stack [100];
	a.top=0;
	if(!a.p)cout<<"errow";
	else cout<<"successfully create";
}在这里插入代码片

后经过改变,将局部函数的参数变为指针,即可较好的完成任务。

#include<iostream>
using namespace std;
typedef int elementtype;
#define stacksize 100
int increase=100;
//顺序栈的实现 (top标志指向栈顶元素上一个单位)
struct stack{
	elementtype top;
	elementtype st[stacksize];
	stack *p;
};
void initstack(stack *a){
	a->p=new stack [100];
	a->top=0;
	if(!a->p)cout<<"errow";
	else cout<<"successfully create";
}

bool push(stack *a,elementtype e){
	if(a->top>=100){
		cout<<"overflow,realloc sapce"<<endl;
		stack *newp=new stack [stacksize+increase];
		if(!newp)cout<<"fail"<<endl;
		else cout<<"please Re-operate all the instrution"<<endl;
		delete []a->p;
		a->p=newp;
	}
	a->st[a->top]=e;
	(a->top)++;
	cout<<a->top;
	return true;
}

elementtype pop(stack *a){
	elementtype e;
	if(a->top<=0)cout<<"errow,the satck is empty"<<endl;
	else{
		(a->top--);
		e=a->st[a->top];
		return e;
	}
}


bool destroy(stack *a){
	delete []a->p;
	cout<<"successfully destroy the stack"<<endl;
	return true;
}

elementtype gettop(stack *a){
	elementtype e;
	if(a->top<=0)cout<<"the stack is empty"<<endl;
	else{
		e=a->st[(a->top)-1];
		return e;
	}
}

bool showstack(stack *a){
	elementtype e;
	int i=(a->top)-1;
	for(;i>=0;i--){
		e=a->st[i];
		cout<<e<<"	";
	}
	if(i<0) cout<<"the end"<<endl;
	return true;
} 


int main(){
	stack sta;
	stack *s=&sta;
	int op=1;
	elementtype e;
	while(op){
	system("cls");
	cout<<"………………………………链表操作……………………………………"<<endl;
	cout<<"1	创建栈		2	销毁栈			"<<endl;
	cout<<"3	入栈		4	出栈			"<<endl;
	cout<<"5	输出栈		6   栈顶元素		"<<endl;
	cout<<"请输入想要操作功能前的数字"<<endl;
	cout<<"输入0退出"<<endl;
	cin>>op;
	switch(op){
		case 1: 
			initstack(s);
			getchar();getchar();
			break;
		case 2:
			destroy(s);
			getchar();getchar();
			break;	
		case 3:
			cout<<"please enter the element you want to push"<<endl;
			cin>>e;
			push(s,e);
			getchar();getchar();
			break;	
		case 4:
			e=pop(s);
			cout<<"the element pop out is "<<e<<endl;
			getchar();getchar();
			break;	
		case 5:
			showstack(s);
			getchar();getchar();
			break;	
		case 6:
			e=gettop(s);
			cout<<"the topelement is "<<e<<endl;
			getchar();getchar();
			break;	
		case 0:
			break;		
	}
	}
	return 0;
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值