C语言一道题的算法分析

来源:百度知道 编辑:UC知道 时间:2024/05/31 22:25:02
#include<stdio.h>
#define m 20
#define elemtype char
typedef struct{
elemtype stack[m];
int top;
}stacknode;
stacknode *sp;
init(stacknode *st){
st->top=0;
return;
}
void push(stacknode *st,elemtype x){
if(st->top==m)
printf("the stack is overflow!\n");
else{
st->top=st->top+1;
st->stack[st->top]=x;
}
}
void pop(stacknode *st){
st->top=st->top-1;
}
int main(){
char s[m];
int i,k;
printf("create a empty stack!\n");
sp=malloc(sizeof(stacknode));
init(sp);
printf("input a expression:\n");
gets(s);
for(i=0;i<strlen(s);i++){
if(s[i]=='(')
push(sp,s[i]);
if(s[i]==')')
pop(sp);
}
if(sp->top==0)
printf("'('match')'!\n");

这个程序主要是验证你所输入的字符串中"("与")"是否配对,若是同个字符串中同时有这两个,就是match,否则就是not match,换句话说,就是两者必须同时出现
下面是我对程序的部分注释,希望你能够更加清楚程序:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define m 20
#define elemtype char
typedef struct{
elemtype stack[m];
int top;
}stacknode;
stacknode *sp;
void init(stacknode *st)//初始化栈,既创建一个空的栈
{
st->top=0;
return;
}
void push(stacknode *st,elemtype x)//往栈里面添加元素
{
if(st->top==m)
printf("the stack is overflow!\n");//因为m定义为20,只要是字符串长度超出了20,就发生上溢
else
{
st->top=st->top+1;
st->stack[st->top]=x;
}
}
void pop(stacknode *st)//栈里面的元素出栈
{
st->top=st->top-1;
}
int main()
{
char s[m];
int i;
printf("create a empty stack!\n");//提示创建了一个空栈
sp=(stacknode *)malloc(sizeof(stacknode))