#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int Status;
typedef int ElemType;
#include<iostream>
#include<string.h>
#include<cstddef>
#include<string.h>
#define MAXSIZE 100//顺序栈储存空间的初始分配量
//- - - - - 顺序栈的存取结构- - - - -
typedef struct {
ElemType* base;//栈底指针
ElemType* top;//栈顶指针
int stacksize;//栈可用的最大容量
}SqStack;
void SystemMenu(SqStack& S) {
cout << "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " << endl;
cout << "|| ||" << endl;
cout << "|| 顺序栈 ||" << endl;
cout << "|| ||" << endl;
cout << "|| ||" << endl;
cout << "|| [1] 初始化 [2] 判空 [3] 求大小 [4] 清除 ||" << endl;
cout << "|| ||" << endl;
cout << "|| [5] 销毁 [6] 入栈 [7] 出栈 [8] 取栈顶元素 ||" << endl;
cout << "|| ||" << endl;
cout << "|| ||" << endl;
cout << "|| [0]退出 ||" << endl;
cout << "- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - " << endl;
cout << "请输入你要选择的:";
}
//初始化
Status InitStack(SqStack& S) {
//构造一个空栈S
S.base = new ElemType[MAXSIZE];//为顺序栈动态分配一个最大容量为MAXSIZE的数组空间
if (!S.base) exit(OVERFLOW);//存储分配失败
S.top = S.base;//top初始为base,空栈
S.stacksize = MAXSIZE;//stacksize置为栈的最大容量MAXSIZE
return OK;
}
//判空
Status StackEmpty(SqStack S) {
//若栈为空,返回true,否则返回false
if (S.top == S.base)
return true;
else
return false;
}
//求大小
int StackLength(SqStack S) {
return S.top - S.base;//求两个指针的差
}
//清除
Status ClaerStack(SqStack S) {
if (S.base)S.top = S.base;
return OK;
}
//销毁
Status DestroyedStack(SqStack& S) {
if (S.base) {
delete S.base;
S.stacksize = 0;
S.base = S.top = NULL;
}
return OK;
}
//入栈
Status Push(SqStack& S, ElemType e) {
//插入元素e为新的栈顶元素
if (S.top - S.base == S.stacksize) return ERROR;//栈满
*S.top++ = e;//将元素e压入栈顶,栈顶指针加1
return OK;
}
//出栈
Status Pop(SqStack& S, ElemType& e) {
//删除s的栈顶元素,用e返回其值
if (S.top == S.base) return ERROR;//栈空
e = *--S.top;
return OK;
}
//取栈顶元素
ElemType GetTop(SqStack S) {
//返回s的栈顶元素,不修改栈顶指针
if (S.top != S.base)
return *(S.top - 1);//返回栈顶元素的值,栈顶指针不变
}
#include<iostream>
#include<string.h>
#include<cstddef>
using namespace std;
int main(int argc, const char* argv[]) {
int n;
int select;
SqStack S;
while (1) {
SystemMenu(S);
cin >> select;
cout << endl;
switch (select)
{
case 0: {
cout << "感谢您的使用,再见!" << endl;
exit(0);
}
case 1: {
InitStack(S);
cout << "顺序栈初始化成功!" << endl;
break;
}
case 2: {
StackEmpty(S);
}
case 3: {
StackLength(S);
}
case 4: {
ClaerStack(S);
}
case 5: {
DestroyedStack(S);
}
case 6: {
Push(S,e);
}
case 7: {
Pop(S,e);
}
case 8: {
GetTop(S);
}
default:
break;
}
}
}
如何在这些代码的基础上实现以下要求
实现从顺序栈中将用户指定的第n个元素出栈并输出
1)顺序栈中第n个元素出栈时,需要先将第n+1到栈顶的所有元素依次出栈,第n个元素出栈后,再将已出栈的元素按原来的次序进栈。
2)要求从键盘输入n,程序要判别n的有效性。
3)第n+1到栈顶的元素在出栈后,为确保能按原序进栈,要求用顺序栈暂存这些出栈元素。
还有在case 7和case 6里e怎么定义
我怎么知道怎么定义?题目都没有,也许是用户输入,也许是文件读取,也许是产生随机数。
你发的这个要求的话,你先把上面的出栈,出栈同时再设一个栈,出一个进一个,然后最后再把那个栈的元素依次出栈,也是出一个进一个