#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node *PtrToNode;
typedef PtrToNode stack;
typedef PtrToNode Position;
struct node
{
char *symbol;
Position next;
};
int Isempty(stack s)
{
return s->next == NULL;
}
void Pop(stack s)
{
Position first;
if(Isempty(s))
printf("Empty stack!\n");
else
{
first = s->next;
s->next = s->next->next;
free(first);
}
}
void MakeEmpty(stack s)
{
if(s == NULL)
printf("Must use CreatStack first!\n");
else
while(!Isempty(s))
Pop(s);
}
stack CreatStack()
{
stack s = (node *)malloc(sizeof(struct node));
if(s == NULL)
printf("Out of space!\n");
s->next = NULL;
MakeEmpty(s);
return s;
}
void Push(char *sign, stack s)
{
Position temp = (node *)malloc(sizeof(struct node));
if(temp == NULL)
printf("Out of space!\n");
else
{
temp->symbol = sign;
temp->next = s->next;
s->next = temp;
}
}
char* Top(stack s)
{
if(!Isempty(s))
return s->next->symbol;
printf("Empty stack!\n");
return 0;
}
int main()
{
char *sign1;
// char *sign2 = ")";
// char *sign3 = "begin";
// char *sign4 = "end";
// char *sign5 = "[";
// char *sign6 = "}";
(1) stack s = CreatStack();
while(scanf("%s", sign1) == 1)
{
//(2) stack s = CreatStack();
if(Isempty(s))
{
(3) if(strcmp(sign1, "(") == 0)
printf("PPPPPPPPPPPP\n");
if(strcmp(sign1, "(") == 0 || strcmp(sign1, "[") == 0 || strcmp(sign1, "{") == 0 || strcmp(sign1, "begin") == 0)
{
Push(sign1, s);
}
else
{
printf("AWrong!!!\n");
break;
}
}
else
{
if(strcmp(sign1, "(") == 0 || strcmp(sign1, "[") == 0 || strcmp(sign1, "{") == 0 || strcmp(sign1, "begin") == 0)
{
Push(sign1, s);
printf("EEEEEEEE\n");
}
else if(strcmp(sign1, ")") == 0 || strcmp(sign1, "]") == 0 || strcmp(sign1, "}") == 0 || strcmp(sign1, "end") == 0)
{
printf("DDDDDDD\n");
if((strcmp(Top(s), "(") == 0 && strcmp(sign1, ")") == 0) || (strcmp(Top(s), "[") == 0 && strcmp(sign1, "]") == 0)||
(strcmp(Top(s), "{") == 0 && strcmp(sign1, "}") == 0) || (strcmp(Top(s), "begin") == 0 && strcmp(sign1, "end") == 0))
{
Pop(s);
printf("GGGGGGGGGGGGGGGGGGG\n");
}
else
{
printf("BWrong!!!\n");
break;
}
}
}
}
if(Isempty(s))
printf("You are right!\n");
else
printf("CWrong!!!\n");
printf("%s\n", Top(s));
return 0;
}
我搞不明白當stack s在while之前的話,只輸入“(”,應該會執行(3)處的if,可事實是不執行
然後我換了下stack s的位置就可以執行了,為什麼???
char *sign1;你沒有為sign1動態分配內存,scanf得到的數據往哪存呀?你可以用char sign1[10];簡單測試一下