思路:两个栈栈底分别为数组两端,栈顶分别向数组中间发展。长度为N的数组在两个栈的元素总数不超过N时不溢出。
代码如下:
// twostacks.cpp : 定义控制台应用程序的入口点。
// 一个数组实现两个栈,从两边开始分别增长
// 最多可容纳n个元素
#include "stdafx.h"
#include <iostream>
#include <vector>
#define N 10
int a[N];
int top1, top2;
using std::cin;
using std::cout;
using std::endl;
using std::cerr;
using std::vector;
void push_s1(int elem)
{
if (top1 < top2 - 1)
{
a[++top1] = elem;
}
else
{
cerr << "s1 overflow!" << endl;
return;
}
}
void push_s2(int elem)
{
if (top2 > top1 + 1)
{
a[--top2] = elem;
}
else
{
cerr << "s2 overflow!" << endl;
}
}
int pop_s1()
{
if (top1 >= 0)
{
--top1;
return a[top1 + 1];
}
else
{
cerr << "s1 underflow!" << endl;
return -1;
}
}
int pop_s2()
{
if (top2 < N)
{
++top2;
return a[top2 - 1];
}
else
{
cerr << "s2 underflow!" << endl;
return -1;
}
}
void show_s()
{
cout << "s1: ";
for (int i = 0; i <= top1; i++)
cout << a[i] << " ";
cout << endl;
cout << "s2: ";
for (int i = N - 1; i >= top2; i--)
cout << a[i] << " ";
cout << endl;
}
int main()
{
top1 = -1; //第一个栈的栈顶
top2 = N; //第二个栈的栈顶
int cmd;
int in;
int out;
while (1)
{
cin >> cmd;
switch (cmd)
{
case 1: //栈1入栈
cin >> in;
push_s1(in);
show_s();
break;
case 2: //栈2入栈
cin >> in;
push_s2(in);
show_s();
break;
case 3: //栈1出栈
cout << pop_s1() << endl;
show_s();
break;
case 4: //栈2出栈
cout << pop_s2() << endl;
show_s();
break;
default:
cerr << "command error!" << endl;
break;
}
}
system("pause");
return 0;
}
运行结果: