这道题折磨了我两个晚上!!!算法很简单,用个栈相信我写JAVA两下就搞定,但是C的结构和指针让人DEBUG到崩溃。。由于没有用malloc分配指针内存,但用了错误结构声明方法,导致变量赋值时无缘无故改变了其他变量的值。。其实我到最后都没弄明白错误的根源。。只知道new一个结构变量的正确方法。。深切感受到C语言基础不牢的惨痛教训啊。再次强调基础真的很重要。K&R的C程序设计语言要常备案头。
解题之前模仿JAVA的Stack类写了个栈。。不知道有没有错,目前没有发现。。有错的话一定求指出啊
ElementType tt = (ElementType) malloc(sizeof(struct Matrix));//对
ElementType tt = malloc(sizeof(ElementType));//错!!!
struct Matrix m;//错!!!
#include<malloc.h>
#include<string.h>
#include<stdio.h>
struct Matrix
{
char c;
int row;
int col;
};
typedef struct Matrix *ElementType;
struct StackRecord
{
int capacity;
int elementCount;
ElementType *elementData;
};
typedef struct StackRecord *Stack;
Stack newStack(int capacity)
{
Stack stack;
stack = malloc(sizeof(struct StackRecord));
stack->elementData = malloc((sizeof(ElementType)) * capacity);
stack->capacity = capacity;
stack->elementCount = 0;
return stack;
}
int empty(Stack s)
{
return s->elementCount == 0;
}
void clear(Stack s)
{
s->elementCount = 0;
}
ElementType pop(Stack s)
{
if (empty(s))
{
printf("Error: Empty stack!");
return (ElementType) NULL;
}
else
return s->elementData[--s->elementCount];
}
ElementType push(Stack s, ElementType data)
{
if (s->elementCount == s->capacity)
{
int oldCapacity = s->capacity;
s->capacity *= 2;
ElementType *newArray = malloc((sizeof(ElementType)) * s->capacity);
memcpy(newArray, s->elementData, (sizeof(ElementType)) * oldCapacity);
free(s->elementData);
s->elementData = newArray;
}
s->elementData[s->elementCount++] = data;
return data;
}
void freeStack(Stack s)
{
if (s != NULL)
{
free(s->elementData);
free(s);
}
}
void print(Stack stack)
{
int j;
for (j = 0; j < stack->elementCount; j++)
{
ElementType e = stack->elementData[j];
printf("%d %d ", e->row, e->col);
}
printf("stack size: %d\n", stack->elementCount);
}
int main()
{
int n;
struct Matrix matrix[26];
scanf("%d", &n);
while (n--)
{
char c[1];
int a, b;
struct Matrix temp;
scanf("%s %d %d", c, &a, &b);
temp.row = a;
temp.col = b;
matrix[c[0] - 'A'] = temp;
}
char s[80];
Stack stack = newStack(30);
while (scanf("%s", s) != EOF)
{
clear(stack);
int i, sum = 0;
for (i = 0; s[i] != '\0'; i++)
{
if (s[i] >= 'A' && s[i] <= 'Z')
push(stack, &matrix[s[i] - 'A']);
else if (s[i] == ')')
{
ElementType b = pop(stack);
ElementType a = pop(stack);
if (a->col != b->row)
{
printf("error\n");
sum = -1;
break;
}
sum += (a->col) * (a->row) * (b->col);
ElementType tt = (ElementType) malloc(sizeof(struct Matrix));
tt->row = a->row;
tt->col = b->col;
push(stack, tt);
}
}
if (sum != -1)
printf("%d\n", sum);
}
freeStack(stack);
return 0;
}