我的代码有问题。它似乎只适用于一位数 int。我不知道如何创建一个适用于大于 9 的 int 的函数。如果字符串为空,我也不知道如何结束程序。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
//stack type
struct node
{
int head;
int *array;
unsigned capacity;
};
struct node* createNode();
int isEmpty();
char pop();
void push(struct node* stack, char op);
int evaluatePostfix();
int main() {
char exp[1000]; // = "5 1 2 + 4 * + 3 -";
printf("Input string:\t");
fgets(exp, 1000, stdin);
for(int i = 1 ; i <= strlen(exp); i++) {
if(exp[i] == '\n') {
exp[i] = '\0';
}
else if (exp[0] == '\n') {
printf("stack is empty\n");
exit(0);
}
}
printf ("%s = %d\n", exp, evaluatePostfix(exp));
return 0;
}
struct node* createNode(unsigned capacity) {
struct node* stack = (struct node*) malloc(sizeof(struct node));
if (!stack) return NULL;
(*stack).head = -1;
(*stack).capacity = capacity;
(*stack).array = (int*) malloc((*stack).capacity *sizeof(int));
if (!(*stack).array) return NULL;
return stack;
}
int isEmpty(struct node *stack) {
return (*stack).head == -1 ;
}
char pop(struct node* stack) {
if (!isEmpty(stack))
return (*stack).array[(*stack).head--] ;
return '$';
}
void push(struct node* stack, char op) {
(*stack).array[++(*stack).head] = op;
}
// The main function that returns value of a given postfix expression
int evaluatePostfix(char* exp) {
// Create a stack of capacity equal to expression size
struct Stack* stack = createStack(strlen(exp));
struct node *stack = createNode(strlen(exp));
if (!stack) return -1;
// Scan all characters one by one
for (int i = 0; exp[i]; ++i){
// If the scanned character is an operand or number,
// push it to the stack.
if ((exp[i])== ' ') continue;
else if (isdigit(exp[i]))
push(stack, exp[i] - '0');
// If the scanned character is an operator, pop two
// elements from stack apply the operator
else
{
int val1 = pop(stack);
int val2 = pop(stack);
switch (exp[i])
{
case '+': push(stack, val2 + val1); break;
case '-': push(stack, val2 - val1); break;
case '*': push(stack, val2 * val1); break;
case '/': push(stack, val2/val1); break;
}
}
}
return pop(stack);
}