当前位置:文档之家› 数据结构实验4_99XXX

数据结构实验4_99XXX

《数据结构》实验报告
实验序号:4 实验项目名称:栈的操作
附源程序清单:
1.
#include <iostream>
#define MaxSize 100
using namespace std;
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack *st) //初始化栈
{
st->top=-1;
}
int StackEmpty(SqStack *st) //判断栈为空{
if(st->top == -1)
return 0;//为空
else
return -1;//不为空
}
void Push(SqStack *st,ElemType x) //元素进栈{
if(st->top==MaxSize-1)
{
printf("栈上溢出!\n");
}
else
{
st->top++; //移动栈顶位置
st->data[st->top]=x; //元素进栈
}
}
void Pop(SqStack *st,ElemType &e) //出栈
{
if(st->top==-1)
{
printf("栈下溢出\n");
}
else
{
e=st->data[st->top]; //元素出栈
st->top--; //移动栈顶位置}
}
int main()
{
SqStack L;
SqStack *st=&L;
ElemType c;
int i;
InitStack(st);
printf("输入回车结束入栈");
while((c=getchar())!='\n')
{
if(c=='(')
Push(st,c);
if((i=StackEmpty(st))==-1)
{
if(c==')')
Pop(st,c);
}
if(c==')' && (i=StackEmpty(st))==0)
{
printf("右括号多出,配对失败");
goto loop;
}
}
if(StackEmpty(st) == -1)
printf("左括号多出,配对失败");
else
printf("配对成功");
loop:
return 0;
}
2.
#include<iostream>
#define MaxSize 100
using namespace std;
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack *st)
{
st->top=-1;
}
int StackEmpty(SqStack *st)
{
return (st->top=-1);
}
void Push(SqStack *st,ElemType *x,int k)
{
int i;
for(i=1;i<k;i++)
{
if(st->top==MaxSize-1)
{
printf("栈上溢出");
}
else
{
st->top++;
st->data[st->top]=x[i-1];
printf("%d\n",st->data[st->top]);
}
}
}
void Pop(SqStack *st,ElemType &e,int k) {
int i;
for(i=1;i<k;i++)
{
if(st->top==-1)
{
printf("栈下溢出");
}
else
{
e=st->data[st->top];
printf("%d\n",e);
st->top--;
}
}
}
int main()
{
SqStack L;
SqStack *st=&L;
ElemType e;
ElemType num[9]={1,2,3,4,5,6,7,8,9};
InitStack(st);
printf("入栈元素是:\n");
Push(st,num,10);
printf("出栈元素是:\n");
Pop(st,e,10);
return 0;
}
3.
#include<iostream>
#include<stack>
using namespace std;
int main()
{
char a,i;
stack<char>s;
while((a=getchar())!='\n')
{
switch(a)
{
case '(':
s.push(a);//入栈
continue;
case '[':
s.push(a);
continue;
case ')':
if(!s.empty())
{
if(s.top()=='(')
{
s.pop(); //出栈
continue;
}
else
{
printf("配对失败1");
goto loop;
}
}
case ']':
if(!s.empty())
{
if(s.top()=='[')
{
s.pop(); //出栈
continue;
}
else
{
printf("配对失败2");
goto loop;
}
s.pop(); //出栈
}
}
}
if(s.empty())
{
printf("配对成功");
}
else
{
printf("配对失败3");
}
loop:
return 0;
}。

相关主题