栈的实现

栈的实现

 

#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_

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值