一个数组实现两个栈

思路:两个栈栈底分别为数组两端,栈顶分别向数组中间发展。长度为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;
}


运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值