题目:
设计算法实现两个栈共享存储空间的基本运算,初始化initstack_d(&S),入栈push(&S,i,e),出栈pop(&S,i,&e)操作。注意两个不同栈顶指针的设置
实现代码:
#include <iostream>
#include<string.h>
using namespace std;
#define stacksize 1024
typedef struct
{
int data[stacksize];
int top1, top2;
//int bot1, bot2;
} doublestacks; //共享栈数据结构的结构体
void initdoublestack(doublestacks &s)
{
s.top1 = -1;
//s->bot1 = -1;
s.top2 = stacksize;
//s->bot2 = stacksize;
}//初始化栈
bool push_doublestack(doublestacks &s, int i, int e)
{
if ((s.top1 + 1) != s.top2)
{
if (i == 1)
{
s.data[++s.top1] = e;
cout << "1栈入栈成功" << endl;
}
else if (i == 2)
{
s.data[--s.top2] = e;
cout << "2栈入栈成功" << endl;
}
return true;
}
else if ((s.top1 + 1) == s.top2)
{
cout << "存储空间已满" << endl;
return false;
}
}
bool pop_doublestack(doublestacks &s, int i, int &e)
{
if (i == 1)
{
if (s.top1 == -1)
{
cout << "栈1为空" << endl;
return false;
}
else
{
if (s.data[s.top1] != e)
{
cout << "出栈号数错误" << endl;
return false;
}
else
{
e = s.data[s.top1--];
cout << "1栈出栈成功" << endl;
return true;
}
}
}
else if (i == 2)
{
if (s.top2 == stacksize)
{
cout << "栈2为空" << endl;
return false;
}
else
{
if (s.data[s.top2] != e)
{
cout << "出栈号数错误" << endl;
return false;
}
else
{
e = s.data[s.top2++];
cout << "2栈出栈成功" << endl;
return true;
}
}
}
}
/*int clear(doublestack *&s)
{ if (!s)
{ return 0;
}
s->top1 = 0;
s->top2 = stacksize - 1;
return 0;
}*/
int main()
{
doublestacks s;
initdoublestack(s);
int n = 3, m = 6;
for (int i = n; i <= m; i++)
{
push_doublestack(s, 1, i);
}
for (int i = n; i <= m; i++)
{
push_doublestack(s, 2, i);
}
for (int j = m; j >= n; j--)
{
pop_doublestack(s, 1, j);
}
for (int j = m; j >= n; j--)
{
pop_doublestack(s, 2, j);
}
return 0;
}