永发信息网

C++中怎么构建栈

答案:5  悬赏:0  手机版
解决时间 2021-03-02 21:29
  • 提问者网友:兔牙战士
  • 2021-03-01 22:56
C++中怎么构建栈
最佳答案
  • 五星知识达人网友:詩光轨車
  • 2021-03-02 00:09
c语言构建栈就可以了,采用的方式是两种,一种是采用数组建栈,一种是采用指针建栈。
#include"stdio.h"
#include"malloc.h"
#include"stdlib.h"
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define TRUE 1
#define FALSE 0

typedef char ElemType;
typedef int Status;

#define STACK_INIT_SIZE 100 //存储空间初始分配量
#define STACKINCREMENT 10 //存储空间分配增量

typedef struct
{
ElemType *base; //在栈构造和销毁之后,base的值为NULL
ElemType *top; //栈顶指针
int stacksize; //当前已分配的存储空间,以元素为单位
}SqStack;

// 构造一个空栈S

Status InitStack(SqStack &S)
{
S.base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(!S.base) //存储分配失败
exit (OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}//InitStack

/////////////////// 若栈不空,则用e返回S的栈顶元素,并返回OK;否则返回ERROR /////

Status GetTop(SqStack S,ElemType &e)
{
if(S.top==S.base)
return ERROR;
e=*(S.top-1);
return OK;
}//GetTop

////////////////// 插入元素e为新的栈顶元素 /////////////////////////////////////

Status Push(SqStack &S,ElemType e)
{
if(S.top-S.base>=S.stacksize) //栈满,追加存储空间
{
S.base=(ElemType *)realloc(S.base,(S.stacksize+STACKINCREMENT) * sizeof(ElemType));
if(!S.base)
exit (OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}//Push

////////////////// 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR

Status Pop(SqStack &S,ElemType &e)
{
if(S.top==S.base)
return ERROR;
e=*--S.top;
return OK;
}//Pop

////////// main() //////////////////////////////
void main()
{
int i;
char ch,e,c;
SqStack S;
InitStack(S);
printf("1.Push\t2.Pop\t3.GetTop\t4.exit\n");
while(1)
{
printf("请选择:");
scanf("%d",&i);
c=getchar(); //*****接受回车符******
switch (i)
{
case 1:
printf("请输入要插入的元素:");
scanf("%c",&ch);
Push(S,ch);
break;
case 2:
printf("弹出栈顶元素:");
Pop(S,e);
printf("%c\n",e);
break;
case 3:
printf("取栈顶元素:");
GetTop(S,e);
printf("%c\n",e);
break;
case 4:
exit(0);
default:
printf("ERROR!Please Reput A Number\n");
}
}
}这就算是一个建栈
全部回答
  • 1楼网友:污到你湿
  • 2021-03-02 02:20
#include
#define LEN 40
class Stack
{
int members[LEN];
int a;
int top;
public:
void init()
{
top = 0;
}
void push(int x)
{
if (top==LEN)
{
cout << "Stack is full!\n";
}
else
{
cout << "入栈: " << x << endl;
members[top] = x;
top++;
}
}
void pop()
{
if (top==0)
{
cout << "Stack is empty!\n";
}
else
{
top--;
cout << "出栈" << endl;
}
}
void dq(char ch)
{
switch(ch)
{
case 'C':
init();
cout << "Create stack" << endl;
break;
case 'T':
if(top==0)
{
cout << "No number!" << endl;
break;
}
else
{
cout << "The top of the stack: " << members[top] << endl;
break;
}
case 'Q':
pop();
break;
case 'P':
cin >> a;
push(a);
break;
}
}
};
void main ()
{
char ch;
Stack s1;
while(cin>>ch)
{
s1.dq(ch);
}
}
  • 2楼网友:归鹤鸣
  • 2021-03-02 02:12
可以用数组模拟
  • 3楼网友:由着我着迷
  • 2021-03-02 01:16
STL 中不是已经定义了栈嘛. Stack 类吧。不用自己写,自己写的bug多,也不高效。
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯