实验二:栈与队列的应用
内容:
(1)输入一个十进制数,利用栈操作,将该数转换成n进制数。
(2)输入一个表达式,表达式中包括三种括号“()”、“[]”和“{}”,判断该表达式的括号是否匹配。
#include<stdio.h>
#include<stdlib.h>
#define max 100
#define add 10
typedef struct node{
int *base;
int top;
int MAXSIZE;
}sqstack;
void Initstack(sqstack &p)
{
p.base=(int*)malloc(sizeof(int));
if (!p.base)
exit(0);
p.top=0;
p.MAXSIZE=max;
}
int Empty(sqstack p)
{
if (p.top==0)
return 1;
return 0;
}
void GetHead(sqstack p)
{
printf("%d\n",p.base[p.top-1]);
}
void Push(sqstack &p,int e)
{
if (p.top>=p.MAXSIZE)
{
p.base=(int*)realloc(p.base,(max+add)*sizeof(int));
if (!p.base)
exit(0);
p.top=max;
p.MAXSIZE+=add;
}
p.base[p.top++]=e; //注意top是先进行传值,然后进行自加
}
void Pop(sqstack &p,int &e)
{
if (p.top==0)
return;
e=p.base[--p.top]; //注意top值是先进行自减,然后进行传值
}
int main()
{
int e,n,m,d;
sqstack p;
printf("请输入想要进行转换的数字:\n");
scanf("%d",&n);
printf("请输入转换成的进制数字:\n");
scanf("%d",&d);
Initstack(p);
while (n)
{
m=n%d;
Push(p,m);
n=n/d;
}
printf("结果为:\n");
while (!Empty(p))
{
Pop(p,e);
printf("%d",e);
}
printf("\n");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#define max 100
#define add 10
typedef struct node{
char *base;
int top;
int MAXSIZE;
}sqstack;
void Initstack(sqstack &p)
{
p.base=(char*)malloc(max*sizeof(char));
if (!p.base)
exit(0);
p.top=0;
p.MAXSIZE=max;
}
int Empty(sqstack p)
{
if (p.top==0)
return 0;
return 1;
}
char GetHead(sqstack p)
{
return p.base[p.top-1];
}
void Push(sqstack &p,char e)
{
if (p.top>=p.MAXSIZE)
{
p.base=(char*)realloc(p.base,(max+add)*sizeof(char));
if (!p.base)
exit(0);
p.top=max;
p.MAXSIZE+=add;
}
p.base[p.top++]=e; //注意top是先进行传值,然后进行自加
}
void Pop(sqstack &p,char &e)
{
if (p.top==0)
return;
e=p.base[--p.top]; //注意top值是先进行自减,然后进行传值
}
int main()
{
int i;
char a[1000],e;
sqstack p;
scanf("%s",a);
Initstack(p);
for (i=0;a[i]!='\0';i++)
{
if (a[i]=='('||a[i]=='['||a[i]=='{')
Push(p,a[i]);
if (a[i]==')'||a[i]==']'||a[i]=='}')
{
Pop(p,e);
if ((e!='('&&a[i]==')')||(e!='['&&a[i]==']')||(e!='{'&&a[i]=='}'))
{
printf("不匹配\n");
return 0;
}
}
}
if (!Empty(p))
printf("匹配\n");
else
printf("不匹配\n");
return 0;
}