Stack

Expression Evaluation

‘+’ ,’-’ ,’‘, ‘/’ , ‘(’ , ‘)’ , ‘%’, ‘*‘。(两个乘号为乘方,具有最高优先级)

#include<bits/stdc++.h>
using namespace std;
struct cunchu
{
    long long zhi;
    bool mode;
};
struct slist
{
    long long d;
    slist *link;
};
void init(slist *&l)
{
    l=new slist;
    l->link=NULL;
}
void push(slist *&l,long long x)
{
    slist *p=new slist;
    p->d=x;
    p->link=l->link;
    l->link=p;
}
bool pop(slist *&l,long long &x)
{
    if (l->link==NULL)
        return 0;
    slist *p=l->link;
    l->link=p->link;
    x=p->d;
    delete p;
    return 1;
}
bool isempty(slist *&l) {return l->link==NULL;}
long long gettop(slist *&l,long long &x)
{
    if (l->link==NULL)
    {
        return 0;
    }
    x=l->link->d;
    return 1;
}
int isp(char s)
{
    if (s=='&')
        return 7;
    if (s=='#')
        return 0;
    if (s=='(')
        return 1;
    if (s=='*'||s=='/'||s=='%')
        return 5;
    if (s=='+'||s=='-')
        return 3;
    if (s==')')
        return 8;
}
int icp(char s)
{
    if (s=='&')
        return 6;
    if (s=='#')
        return 0;
    if (s=='(')
        return 8;
    if (s=='*'||s=='/'||s=='%')
        return 4;
    if (s=='+'||s=='-')
        return 2;
    if (s==')')
        return 1;
}
void js(slist *&l,int op)
{
    long long left,right;
    pop(l,right);
    pop(l,left);
    switch(op)
    {
        case '+':push(l,left+right);break;
        case '-':push(l,left-right);break;
        case '*':push(l,left*right);break;
        case '/':push(l,left/right);break;
        case '%':push(l,left%right);break;
        case '&':
            long long ttmp=pow(left,right);
            push(l,ttmp);
            break;
    }
}
int main()
{
    string s;
    while (cin>>s)
    {
        if (s[0]=='-'||s[0]=='+')
            s="0"+s;
        for (int i=0;i<s.size();++i)
        {
            if (s[i]=='(')
            {
                if (s[i+1]=='-'||s[0]=='+')
                {
                    i++;
                    s.insert(i,"0");
                }
            }
            if (s[i]=='*'&&s[i+1]=='*')
            {
                s[i]='&';
                string::iterator it=s.begin();
                it+=i+1;
                s.erase(it);
                i--;
            }
        }
        s+="#";
        slist *l;
        init(l);
        push(l,'#');
        int wz=0;
        vector<cunchu> hz;
        long long x;
        while (!isempty(l)&&wz!=s.size()+1)
        {
            if (isdigit(s[wz]))
            {
                int tmp=0;
                while (isdigit(s[wz]))
                {
                    tmp=tmp*10+s[wz]-48;
                    wz++;
                }
                cunchu hhh;
                hhh.zhi=tmp;
                hhh.mode=1;
                hz.push_back(hhh);
            }
            else
            {
                gettop(l,x);
                if (isp(x)<icp(s[wz]))
                {
                    push(l,s[wz]);
                    wz++;
                }
                else if (isp(x)>icp(s[wz]))
                {
                    long long op;
                    pop(l,op);
                    cunchu hhh;
                    hhh.zhi=op;
                    hhh.mode=0;
                    hz.push_back(hhh);
                }
                else
                {
                    long long op;
                    pop(l,op);
                    if (op=='(')
                        wz++;
                }
            }
        }
        slist *open;
        init(open);
        long long ans;
        wz=0;
        for (int i=0;i<hz.size();++i)
        {
            if (!hz[i].mode)
                js(open,hz[i].zhi);
            else
                push(open,hz[i].zhi);
        }
        pop(open,ans);
        cout<<ans<<endl;

    }
}

Check for balanced parentheses in an expression

#include<stdio.h>
#include<stdlib.h>
#define bool int

/* structure of a stack node */
struct sNode
{
   char data;
   struct sNode *next;
};

/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data);

/* Function to pop an item from stack*/
int pop(struct sNode** top_ref);

/* Returns 1 if character1 and character2 are matching left
   and right Parenthesis */
bool isMatchingPair(char character1, char character2)
{
   if (character1 == '(' && character2 == ')')
     return 1;
   else if (character1 == '{' && character2 == '}')
     return 1;
   else if (character1 == '[' && character2 == ']')
     return 1;
   else
     return 0;
}

/*Return 1 if expression has balanced Parenthesis */
bool areParenthesisBalanced(char exp[])
{
   int i = 0;

   /* Declare an empty character stack */
   struct sNode *stack = NULL;

   /* Traverse the given expression to check matching parenthesis */
   while (exp[i])
   {
      /*If the exp[i] is a starting parenthesis then push it*/
      if (exp[i] == '{' || exp[i] == '(' || exp[i] == '[')
        push(&stack, exp[i]);

      /* If exp[i] is an ending parenthesis then pop from stack and 
          check if the popped parenthesis is a matching pair*/
      if (exp[i] == '}' || exp[i] == ')' || exp[i] == ']')
      {

          /*If we see an ending parenthesis without a pair then return false*/
         if (stack == NULL)
           return 0; 

         /* Pop the top element from stack, if it is not a pair 
            parenthesis of character then there is a mismatch.
            This happens for expressions like {(}) */
         else if ( !isMatchingPair(pop(&stack), exp[i]) )
           return 0;
      }
      i++;
   }

   /* If there is something left in expression then there is a starting
      parenthesis without a closing parenthesis */
   if (stack == NULL)
     return 1; /*balanced*/
   else
     return 0;  /*not balanced*/
} 

/* UTILITY FUNCTIONS */
/*driver program to test above functions*/
int main()
{
  char exp[100] = "{()}[]";
  if (areParenthesisBalanced(exp))
    printf("\n Balanced ");
  else
    printf("\n Not Balanced ");  
  return 0;
}    

/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
  /* allocate node */
  struct sNode* new_node =
            (struct sNode*) malloc(sizeof(struct sNode));

  if (new_node == NULL)
  {
     printf("Stack overflow \n");
     getchar();
     exit(0);
  }           

  /* put in the data  */
  new_node->data  = new_data;

  /* link the old list off the new node */
  new_node->next = (*top_ref);  

  /* move the head to point to the new node */
  (*top_ref)    = new_node;
}

/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
  char res;
  struct sNode *top;

  /*If stack is empty then error */
  if (*top_ref == NULL)
  {
     printf("Stack overflow \n");
     getchar();
     exit(0);
  }
  else
  {
     top = *top_ref;
     res = top->data;
     *top_ref = top->next;
     free(top);
     return res;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值