厦门理工学院数据结构实验4

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

《数据结构》实验报告

实验序号:4 实验项目名称:栈的操作

2.C/C++的库函数中已经实现了栈,实例如下:

2.判别一个算术表达式中的圆括号和方括号配对是否正确。

附源程序清单:

1.

#include

#include

#include

#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) //元素进栈{

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--; //移动栈顶位置}

}

void Push1(SqStack *st) //元素进栈

{

int x[5];

int i;

if(st->top==MaxSize-1)

{

printf("栈上溢出!\n");

}

else

{

printf("请输入5个元素:");

for(i=0;i<5;i++)

scanf("%d",&x[i]);

for(i=4;i>=0;i--)

{

st->top++; //移动栈顶位置

st->data[st->top]=x[i]; //元素进栈

}

}

}

void Pop1(SqStack *st) //出栈

{

int i,x[5];

if(st->top==-1)

{

printf("栈下溢出\n");

}

else

{

for(i=0;i<5;i++)

{

x[i]=st->data[st->top]; //元素出栈

st->top--; //移动栈顶位置}

printf("出栈数组为:\n");

for(i=0;i<5;i++)

printf("%d ",x[i]);

printf("\n");

}

}

int main()

{

SqStack L;

SqStack *st=&L;

ElemType e;

int i,x[5],a;

InitStack(st);

Push1(st);

Push1(st);

Push1(st);

Pop1(st);

/*for(i=1;i<10;++i)

{

Push(st,i);

printf("入栈元素是:%d\n",i);

}

for(i=1;i<10;++i)

{

Pop(st,e);

printf("出栈元素是:%d\n",e);

}*/

return 0;

}

2.

#include //引入栈

using namespace std;

void main()

{

int sign=1;

char a,b='(';

stacks;

printf("请输入算术表达式,以'#'为结束标志:\n");

a=getchar();

while(a!='#')

{

switch(a)

{

case '(':

s.push(a);

break;

case ')':

if(s.top()=='(')

s.pop();

else

sign=0;

break;

}

if(sign==0)

break;

else

a=getchar();

}

if(s.empty()==NULL)

sign=0;

if(sign==1)

printf("圆括号配对正确!\n");

else

printf("圆括号配对错误!\n");

}

相关文档
最新文档