手写栈和队列实现计算器

 要求

字符串读入,含义+,-,*,/,(,)
数据含小数

思路

字符串截取读入(数字位数可能不为一位)
template简化代码复杂度
enum增加代码可读性
class 抽象出栈
 ~~~~namespace定义域~~好玩~~


main函数

#include <bits/stdc++.h>

#define stack

#define rep(i,a,b) for(int i=a;i<=b;i++)

std::string s;
#ifdef queue
#include "queue.hpp"
#endif

#ifdef stack
#include "stack.hpp"
My_stack::Stack <double> q1;
My_stack::Stack <char> q2;
#endif

void work()
{
        char c2;
        q2.get_top(c2);q2.pop();
        double a1,a2;
        q1.get_top(a1);q1.pop();
        q1.get_top(a2);q1.pop();
        std::cout<<c2<<" "<<a1<<" "<<a2<<'\n';
       // std::cout<<a1+a2;
        if(c2=='+') q1.push(a1+a2);
        else if(c2=='-')
        {
                q1.push(a2-a1);
        }
        else if(c2=='/')
        {
                q1.push(a2/a1);
        }
        else if(c2=='*')
        {
                q1.push(a1*a2);
        }
}

int main()
{
        #ifdef stack
        
        std::cin>>s;
        rep(i,0,s.length()-1)
        {
                if(s[i]<='9'&&s[i]>='0') 
                {
                        int id1=0;
                        rep(j,i,s.length()-1)
                        {
                                if(s[j]=='/'||s[j]=='*'||s[j]=='+'||s[j]=='-')
                                {
                                        id1=j;break;
                                }
                        }
                        if(!id1) id1=s.length()-1;
                        std::string s2=s.substr(i,id1-i);
                        std::cout<<s2<<'\n';
                        char s_2[50]={0};
                        rep(j,0,s2.length()-1)
                        {
                                s_2[j]=s2[j];
                        }
                        i=id1-1;
                        double ans=atof(s_2);
                        q1.push(ans);
                }
                else if(s[i]=='+'||s[i]=='-')
                {	//std::cout<<"dwq";
                        while(!q2.empty()&&(q2.top()=='+'||q2.top()=='-'||q2.top()=='*'||q2.top()=='/'))
                        {
                        	
                                        work();
                        }
                        q2.push(s[i]);
                }
                else if(s[i]=='*'||s[i]=='/')
                {
                        while(!q2.empty()&&(q2.top()=='*'||q2.top()=='/'))
                        {
                                work();
                        }
                        q2.push(s[i]);
                }
                else if(s[i]=='(') q2.push(s[i]);
                else if(s[i]==')')
                {
                        while(q2.top()!='(')
                        {
                                work();
                        }
                        q2.pop();
                }
        }
        while(!q2.empty())
        {
        	work();
        }
        double ans=0;
        q1.get_top(ans);
        std::cout<<ans<<'\n';
        #endif
        #ifdef queue
        My_queue::Queue <int> q;
        rep(i,1,5) q.push(i);
        rep(i,1,2) q.pop();
        rep(i,6,8) q.push(i);
        rep(i,1,1) q.pop();
        int n;
        q.get_front(n);
        std::cout<<n<<'\n';
        #endif
        return 0;
}

//stack.cpp

#include <iostream>

enum error_code {success,overflow,underflow};

namespace My_stack
{
        template<class T>
        class Stack
        {
        public:
        Stack();
        ~Stack();
        bool empty() const;
        bool full() const;
        error_code get_top(T &a) const;
        error_code push(T a) ;
        double top() ;
        error_code pop() ;
        
        private:
        T* my_date;
        int max_size;
        int cnt;
        };
        
        template <class T> Stack<T>::Stack()
        {
                this->max_size=10000;
                this->cnt=0;
                my_date = new T [max_size];
        }
        template <class T> Stack<T>::~Stack()
        {
                delete my_date;
        }
        template <class T> bool Stack<T>::full() const
        {
                if(this->cnt==this->max_size) return 1;
                else return 0;
        }
        template <class T> bool Stack<T>::empty() const
        {
                if(this->cnt==0) return 1;
                else return 0;
        }
        template <class T> error_code Stack<T>::get_top(T &a) const
        {
                if(this->empty()) return underflow;
                else 
                {
                        a = my_date[cnt-1];
                        return success;
                }        
        }
        template <class T>  double Stack<T>::top() 
        {
                if(!empty()) return my_date[cnt-1];
        }
        template <class T> error_code Stack<T>::push(T a) 
        {
                if(full()) return overflow;
                else 
                {
                my_date[cnt]=a;
                cnt++;
                //std::cout<<cnt<<'\n';
                return success;
                }
        }
        template <class T> error_code Stack<T>::pop() 
        {
                if(this->empty()) return overflow;
                else 
                {
                        my_date[cnt-1]=0;
                        --cnt;
                        return success;
                }
        }
}

//附赠queue抽象

#include <iostream>

enum error_code {success,overflow,underflow};

const int max_size=1000;

namespace My_queue
{
        template<class T>
        class Queue
        {
        public:
        Queue();
        ~Queue();
        bool empty() const;
        bool full() const;
        error_code get_front(T &a) const;
        error_code push(T a) ;
        error_code pop() ;
        private:
        T* my_date;
        int cnt;
        int left;
        int right;
        };
        
        template <class T> Queue<T>::Queue()
        {
                this->cnt=0;
                this->left=this->right=0;
                my_date = new T [max_size];
        }
        template <class T> Queue<T>::~Queue()
        {
                delete my_date;
        }
        template <class T> bool Queue<T>::full() const
        {
                if(this->cnt==max_size) return 1;
                else return 0;
        }
        template <class T> bool Queue<T>::empty() const
        {
                if(this->cnt==0) return 1;
                else return 0;
        }
        template <class T> error_code Queue<T>::get_front(T &a) const
        {
                if(this->empty()) return underflow;
                else 
                {
                        a = my_date[(left+1)%max_size];
                        return success;
                }        
        }
        template <class T> error_code Queue<T>::push(T a) 
        {
                if(full()) return overflow;
                else 
                {
                right=(++right)%max_size;
                my_date[right]=a;
                cnt++;
                //std::cout<<cnt<<'\n';
                return success;
                }
        }
        template <class T> error_code Queue<T>::pop() 
        {
                if(this->empty()) return overflow;
                else 
                {
                        left=(left+1)%max_size;
                        //y_date[left]=0;
                        --cnt;
                        return success;
                }
        }
}

 

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
#include <stdio.h> #include <stdlib.h> #define MAX_SIZE 100 // 定义栈的最大容量 typedef struct { int top; // 栈顶指针 int* data; // 栈内数据存储数组 } Stack; // 初始化栈 void initStack(Stack* s) { s->data = (int*)malloc(MAX_SIZE * sizeof(int)); // 动态分配内存 s->top = -1; // 初始化栈顶指针 } // 判断栈是否为空 int isEmpty(Stack* s) { return s->top == -1; } // 判断栈是否已满 int isFull(Stack* s) { return s->top == MAX_SIZE - 1; } // 入栈 void push(Stack* s, int x) { if (isFull(s)) { printf("Stack is full.\n"); return; } s->top++; // 栈顶指针加1 s->data[s->top] = x; // 将数据存储到栈顶位置 } // 出栈 int pop(Stack* s) { if (isEmpty(s)) { printf("Stack is empty.\n"); return -1; } int x = s->data[s->top]; // 取出栈顶元素 s->top--; // 栈顶指针减1 return x; } // 获取栈顶元素 int peek(Stack* s) { if (isEmpty(s)) { printf("Stack is empty.\n"); return -1; } return s->data[s->top]; } // 判断字符是否为操作符 int isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } // 计算表达式 int calculate(int a, int b, char op) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; default: return 0; } } // 计算表达式(后缀表达式) int evaluate(char* postfix) { Stack s; initStack(&s); char* p = postfix; while (*p != '\0') { if (*p >= '0' && *p <= '9') { // 如果是数字,将其入栈 int num = *p - '0'; while (*(p+1) >= '0' && *(p+1) <= '9') { // 处理多位数字 num = num * 10 + *(++p) - '0'; } push(&s, num); } else if (isOperator(*p)) { // 如果是操作符,弹出栈顶的两个数字进行计算 int b = pop(&s); int a = pop(&s); int result = calculate(a, b, *p); push(&s, result); } p++; } return pop(&s); // 最后栈内只剩下一个结果,返回它 } int main() { char infix[100]; // 中缀表达式 printf("Enter an infix expression: "); scanf("%s", infix); // 将中缀表达式转换为后缀表达式 char postfix[100]; // 后缀表达式 Stack s; initStack(&s); char* p = infix; char* q = postfix; while (*p != '\0') { if (*p >= '0' && *p <= '9') { // 如果是数字,直接输出到后缀表达式 *(q++) = *p; } else if (*p == '(') { // 如果是左括号,入栈 push(&s, *p); } else if (*p == ')') { // 如果是右括号,弹出栈内所有操作符并输出到后缀表达式,直到遇到左括号 while (!isEmpty(&s) && peek(&s) != '(') { *(q++) = pop(&s); } pop(&s); // 弹出左括号 } else if (isOperator(*p)) { // 如果是操作符 while (!isEmpty(&s) && peek(&s) != '(' && ((*p == '+' || *p == '-') && (peek(&s) == '*' || peek(&s) == '/'))) { // 如果栈顶有更高优先级的操作符,则弹出栈顶操作符并输出到后缀表达式 *(q++) = pop(&s); } push(&s, *p); // 将当前操作符入栈 } p++; } while (!isEmpty(&s)) { // 将栈内剩余的操作符输出到后缀表达式 *(q++) = pop(&s); } *q = '\0'; // 末尾添加结束符 printf("Postfix expression: %s\n", postfix); int result = evaluate(postfix); printf("Result: %d\n", result); return 0; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值