#include
using namespace std;
#define MaxSize 100
//顺序栈的初始分配空间大小
typedef int ElemType;
//假设顺序栈中所有元素为int类型
typedef struct
{
ElemType data[MaxSize];
//保存栈中元素
int top;
//栈顶指针
}SqStack;
//顺序栈类型
int Push(SqStack&st,ElemType x)//进栈元
{
if (st.top==MaxSize-1)
return 0;
else
{
st.top++;
st.data[st.top]=x;
return 1;
}
}
int StackEmpty(SqStack st)
//判断栈是否为空
{
if(st.top==-1)
return 1;
else return 0;
}
int Pop(SqStack &st,SqStack&tmpst,ElemType &x) ///st,15
//出栈元素x
{
if(st.top==-1)
//栈空
return 0;
else if(st.data[st.top]==15) //等于15的时候出栈
{
x=st.data[st.top];
st.top--;
return 1;
}
else //不是值为15的 出栈并且存到临时栈tmpst中
{
tmpst.data[tmpst.top]=st.data[st.top];
st.top--;
tmpst.top++;
return 1;
}
int lop(SqStack &st,ElemType &x){
if(tmpst.top==-1)
return 0;//栈空
else
x=st.data[st.top]
st.top--;
rerturn 1;
}
void expand_action()
{
printf("初始化栈st\n");
SqStack st,tmpst;
ElemType e,t;
InitStack(st);
InitStack(tmpst);
printf("栈%s\n",(StackEmpty(st)==1?"空":"不空"));
Push(st,10);
Push(st,15);
Push(st,20);
Push(st,15);
Push(st,15);
Push(st,60);
printf("元素10 15 20 15 15 60依次进栈st\n");
printf("退栈所有值为15的元素\n");
int t=15;//
Pop(st,t);//t=15
printf("栈%s\n",(StackEmpty(st)==1?"空":"不空"));
printf("出栈序列为");
while(!StackEmpty(st))
{
Pop(st,e);
printf("%c",e);
}
}
int main()
{
//
expand_action;
return 0;
}
不太明白怎么写 有没有老哥看看怎么弄
修改如下,供参考:
#include <stdio.h>
#define MaxSize 100
//顺序栈的初始分配空间大小
typedef int ElemType;
//假设顺序栈中所有元素为int类型
typedef struct
{
ElemType data[MaxSize];//保存栈中元素
int top; //栈顶指针
}SqStack;
//顺序栈类型
void InitStack(SqStack& st)
{
st.top = -1;
}
void DestroyStack(SqStack& st)
{
st.top = -1;
printf("销毁栈\n");
}
int Push(SqStack& st,ElemType x)//进栈元
{
if (st.top==MaxSize-1)
return 0;
else{
st.top++;
st.data[st.top]=x;
return 1;
}
}
int Pop(SqStack& st,ElemType &x) //出栈
{
if(st.top==-1)
return 0;//栈空
x = st.data[st.top];
st.top--;
return 1;
}
int StackEmpty(SqStack st) //判断栈是否为空
{
if(st.top==-1)
return 1;
else
return 0;
}
int lop(SqStack& st, ElemType x) //删除所有为 x 的元素
{
SqStack tmpst;//临时栈 tmpst
ElemType e;
InitStack(tmpst);
if(st.top==-1)//栈空
return 0;
else{
while(!StackEmpty(st))
{
Pop(st,e);
if (e != x)
Push(tmpst,e);
}
while(!StackEmpty(tmpst))
{
Pop(tmpst,e);
Push(st,e);
}
}
DestroyStack(tmpst);//销毁临时栈
return 1;
}
void expand_action()
{
SqStack st; //,tmpst;
ElemType e,t; //InitStack(tmpst);
printf("初始化栈st\n");
InitStack(st);
printf("栈%s\n",(StackEmpty(st)==1?"空":"不空"));
Push(st,1);
Push(st,2);
Push(st,2);
Push(st,1);
Push(st,2);
Push(st,3);
printf("元素1,2,2,1,2,3依次进栈\n");
printf("删除所有元素2\n");
lop(st,2);
printf("出栈序列:");
while(!StackEmpty(st))
{
Pop(st,e);
printf("%d",e);
}
}
int main()
{
expand_action(); //expand_action
return 0;
}