刚学习栈和队列自己编写判断括号的程序却编译不过,请大家帮忙看看。
源代码见下:
×××××××××××××××××××××××××××××××××××××
/*判断公式的正确性*/
#include <stdio.h>
typedef struct cha/*定义结点结构体*/
{
char data;
struct cha *next;
}*slink;
typedef struct/*定义栈结构体*/
{
slink top;
int length;
}stack;
void initstack(stack &s)/*初始化一个空栈*/
{
s.top=NULL;
s.length=0;
}
void push(stack &s,char c)/*压栈操作*/
{
v=(slink)malloc(sizeof(struct cha));
v-> data=c;
v-> next=s.top;
s.top=v;
s.length++;
}
void pop(stack &s,char *c)/*出栈操作*/
{
if(s.top==NULL)
{printf( "the stack is empty. ");*c=NULL;}
else
{*c=s.top-> data;s.top=s.top-> next;s.length--;}
}
main()
{
stack s;
char str[30],*p,c;
p=str;
printf( "\nplease input a string: ");
scanf( "%s ",p);
initstack(&s);
while(*p)
{
if (*p== '( '||*p== '[ '||*p== '{ ')push(&s,*p++);
else if(*p== ') '||*p== '] '||*p== '} ')
{
pop(&s,&c);
switch(c)
{
case '( ':if(*p!= ') ')printf( "\nthe ) not find ( . ");
break;
case '[ ':if(*p!= '] ')printf( "\nthe ] not find [ . ");
break;
case '{ ':if(*p!= '} ')printf( "\nthe } not find { . ");
break;
default:printf( "\nin front part of the string can 't find the ( or [ or {. ");
}
p++;
}
}
getch();
}
[解决办法]
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
typedef struct cha/*¶¨Òå½áµã½á¹¹Ìå*/
{
char data;
struct cha *next;
}*slink;
typedef struct/*¶¨ÒåÕ»½á¹¹Ìå*/
{
slink top;
int length;
}stack;
void initstack(stack &s)/*³õʼ»¯Ò»¸ö¿ÕÕ»*/
{
s.top=NULL;
s.length=0;
}
void push(stack &s,char c)/*ѹջ²Ù×÷*/
{
slink v=(slink)malloc(sizeof(struct cha));
v-> data=c;
v-> next=s.top;
s.top=v;
s.length++;
}
void pop(stack &s,char *c)/*³öÕ»²Ù×÷*/
{
if(s.top==NULL)
{printf( "the stack is empty. ");*c=NULL;}
else
{*c=s.top-> data;s.top=s.top-> next;s.length--;}
}
int main()
{
stack s;
char str[30],*p,c;
p=str;
printf( "\nplease input a string: ");
scanf( "%s ",p);
initstack(s);
while(*p)
{
if (*p== '( '||*p== '[ '||*p== '{ ')push(s,*p++);
else if(*p== ') '||*p== '] '||*p== '} ')
{
pop(s,&c);
switch(c)
{
case '( ':if(*p!= ') ')printf( "\nthe ) not find ( . ");
break;
case '[ ':if(*p!= '] ')printf( "\nthe ] not find [ . ");
break;
case '{ ':if(*p!= '} ')printf( "\nthe } not find { . ");
break;
default:printf( "\nin front part of the string can 't find the ( or [ or {. ");
}
p++;
}
}
getch();
return 0;
}