用一个数组实现两个堆栈,要求最大利用数组空间,使数组只要有空间入栈操作就能成功。
#include<iostream>
#include<bits/stdc++.h>
#define MAXSIZE 1024//最大长度
using namespace std;
typedef int ElementType;
typedef struct DStack{
ElementType Data[MAXSIZE];
int Top1;//第一个栈 栈顶
int Top2;//第二个栈 栈顶
}*DS;
//初始化
DS initDS()
{
DS PrtS=(DS)malloc(sizeof(DS));
PrtS->Top1=-1;//栈空
PrtS->Top2=MAXSIZE;
cout<<"初始化完成"<<endl;
return PrtS;
}
void Push(DS PrtS,ElementType x,int Tag)//Tag用于分辨贮存至哪一个栈,0表示栈1,1表示栈2
{
if(PrtS->Top1==PrtS->Top2)//类似快速排序,top1==top2时栈满
{
cout<<"栈满"<<endl;
return;
}
// cout<<"Push"<<endl; //用于查看调用情况
if(Tag)
{
// cout<<"top2"<<ends<<PrtS->Top2<<ends;
PrtS->Data[--(PrtS->Top2)]=x;//入栈 栈1 top++ 栈2 top--
// cout<<PrtS->Top2<<endl;
}
else {
// cout<<"top1&#
【数据结构】【c/c++描述】用一个数组实现两个堆栈,最优利用空间
最新推荐文章于 2024-07-18 00:08:52 发布