栈的实现
#include <stdio.h>
#include "seqstack.h"
int main()
{
char rpn[] = "300 4 2 +*2 /5 -";
printf("%d\n", rpn_evaluation(rpn));
return 0;
}
-------------------------------------------------------------------------
#include "seqstack.h"
#include <malloc.h>
Pseqstack create_null_sqstack(int m)
{
Pseqstack pastack;
pastack = (Pseqstack)malloc(sizeof(struct seqstack));
pastack->maxnum = m;
pastack->top = -1;
pastack->s = (int*)malloc(sizeof(int) * m);
return pastack;
}
void push_seq(Pseqstack pastack, int x)
{
pastack->s[++pastack->top] = x;
}
void pop_seq(Pseqstack pastack)
{
pastack->top--;
}
int top_seq(Pseqstack pastack)
{
return pastack->s[pastack->top];
}
int rpn_evaluation(char* str)
{
Pseqstack st;
st = create_null_sqstack(100);
for(int i = 0; str[i] != '\0'; i++)
if(str[i] >= '0' && str[i] <= '9'){
push_seq(st, str[i] - '0');
while(str[++i] != ' '){
int temp = top_seq(st);
pop_seq(st);
push_seq(st, temp * 10 + str[i] - '0');
}
}
else{
int operand2 = top_seq(st);
pop_seq(st);
int operand1 = top_seq(st);
pop_seq(st);
switch(str[i]){
case '+':
push_seq(st, operand1 + operand2);
break;
case '-':
push_seq(st, operand1 - operand2);
break;
case '*':
push_seq(st, operand1 * operand2);
break;
case '/':
push_seq(st, operand1 / operand2);
break;
}
}
return top_seq(st);
}
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
#ifndef _SEQSTACK_H_
#define _SEQSTACK_H_
struct seqstack
{
int maxnum;
int top;
int* s;
};
typedef struct seqstack* Pseqstack;
Pseqstack create_null_sqstack(int m);
void push_seq(Pseqstack pastack, int x);
void pop_seq(Pseqstack pastack);
int top_seq(Pseqstack pastack);
int rpn_evaluation(char* str);
#endif // _SEQSTACK_H_