题目:
若有一个顺序栈,其中含有一些值为x的元素,试采用算法将x从栈中清除。
分析:
由于栈是一个先进先出的序列,若要将栈中值为x的元素进行清除,则需要将栈中所有的元素出栈再进栈,在这一过程中,对所有值为x的元素均进行筛选。
题解:
首先建立一个和栈有关的算法:
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 10;
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize]; //存放栈中的数据元素
int top; //栈顶指针,即存放栈顶元素在data数组的下标
}SqStack; //顺序栈类型
void InitStack(SqStack *&s) //初始化栈
{
s=(SqStack *)malloc(sizeof(SqStack)); //分配一个顺序栈空间,首地址存放在s中
s->top=-1; //栈顶指针置为-1
}
void DestroyStack(SqStack *&s) //销毁栈
{
free(s);
}
bool StackEmpty(SqStack *s) //判断栈是否为空
{
return(s->top==-1);
}
bool Push(SqStack *&s,ElemType e) //进栈
{
if(s->top==MaxSize-1)
return false; //栈满的情况,即栈上溢出
s->top++; //栈顶指针增1
s->data[s->top]; //元素e放在栈顶指针处
return true;
}
bool Pop(SqStack *&s,ElemType &e)
{
if(s->top==-1) return false;
e=s->data[s->top];
}
bool GetTop(SqStack *s,ElemType &e)
{
if(s->top==-1) return false; //栈为空的情况,即栈下溢出
e=s->data[s->top]; //取栈顶元素
return true;
}
然后通过所有元素在两个栈之间的进出来筛选符合要求的元素(即非x)的元素。
void fun(SqStack *&st,ElemType x)
{
SqStack *tmps;
ElemType e;
InitStack(tmps); //建立一个临时栈并初始化
while(!StackEmpty(st))
{
Pop(st,e); //退栈st中的所有元素,将不为x的元素进栈到tmps中
if(e!=x) Push(tmps,e);
}
while(!StackEmpty(tmps))
{
Pop(tmps,e); //退栈tmps中的所有元素,并进栈到st中
Push(st,e);
}
DestroyStack(tmps); //销毁栈tmps
}
本算法的功能是如果栈中存在元素x,将其从栈中清除。