实验目的:
掌握栈的顺序
表
关于同志近三年现实表现材料材料类招标技术评分表图表与交易pdf视力表打印pdf用图表说话 pdf
示和实现
实验内容:
编写一个程序实现顺序栈的各种基本运算。
实验步骤:
1. 初始化顺序栈
2. 插入元素
3. 删除栈顶元素
4. 取栈顶元素
5. 遍历顺序栈
6. 置空顺序栈
实验实现
程序如下:
#include "stdio.h"
#include "malloc.h"
typedef struct
{
char stack[10];
int top;
}SeqStack;
void Push(SeqStack *head,char x)
{
if(head->top==9) printf("此栈以满,无法入栈\n"); else
{
head->top++;
head->stack[head->top]=x;
}
}
void Pop(SeqStack *head)
{
if(head->top==-1) printf("此栈为空,无法出栈\n"); else head->top--;
}
char GetTop(SeqStack *head)
{
if(head->top==-1) printf("此栈为空\n");
else return head->stack[head->top];
}
int StackEmpty(SeqStack *head)
{
if(head->top==-1) return 1;
return 0;
}
void CreatStack(SeqStack *head)
{
char x;
printf("请输入表达式\n");
while(1)
{
scanf("%c",&x);
if(x=='\n') break;
if(x=='('||x=='['||x=='{') Push(head,x);
switch(x)
{
case ')':
{
GetTop(head)=='('?Pop(head):Push(head,x);
break;
}
case ']':
{
GetTop(head)=='['?Pop(head):Push(head,x);
break;
}
case '}':
{
GetTop(head)=='{'?Pop(head):Push(head,x);
}
}
}
}
void main()
{
int a;
char ch;
SeqStack *head;
head=(SeqStack*)malloc(sizeof(SeqStack));
do
{
head->top=-1;
CreatStack(head);
StackEm pty(head)?printf("此表达式括号匹配\n"):printf("此表达式括号不匹配\n"); printf("输入1继续,0退出\n");
scanf("%d%c",&a,&ch);
}while(a);
}