Algorithmic---Conversion of single-letter variable expressions with subtraction and parentheses into inverse polish

Source: Internet
Author: User

#include <stdio.h>#include<stdlib.h>#include<malloc.h>#defineStack_init_size 100#defineStack_increament 10#pragmaWarning (disable:4996)//I use the vs2015, do not add this sentence with scanf will error (using unsafe function)typedefstruct{//Stack    Char*Base; Char*top; intStackSize;} Stack;voidInitstack (Stack &stack) {//Initialize StackStack.Base= Stack.top = (Char*)malloc(sizeof(Char) *stack_init_size); Stack.stacksize=stack_init_size;}voidPush (Stack &s,CharP) {//into the stack    if(S.top-s.Base>=s.stacksize) {S.Base= (Char*)realloc(S.Base, (s.stacksize + stack_increament) *sizeof(Char)); S.top= S.stacksize + S.Base; S.stacksize+=stack_increament; }    *s.top++ =p;}voidPop (Stack &stack,Char&AMP;P) {//out of the stack    if(Stack.Base==stack.top) {p= NULL;return; } P= *--stack.top;}CharGetTop (Stack stack) {//get top of stack element    if(Stack.Base= = Stack.top)returnNULL; return* (Stack.top-1);}Char*nibolan (Char*E)/*returns the inverse polish of an expression e*/{//the stack s1 is used for storing operators, and the stack S2 is used to store inverted PolishStack S1, S2;initstack (S1); Initstack (S2); Push (S1,'#'); //Suppose that the character ' # ' is the operator with the lowest operation level and is pressed into the stack S1//The P pointer is used to traverse the incoming string, CH is used to temporarily hold the character, and length is used to calculate the string length    Char*p = e, ch;intLength =0;  for(; *p! =' /'; p++)//Per- character Access    {        Switch(*p) {//' (' then directly into the stack S1//' ) ' will be the nearest ' (' operator from the top of the stack S1 stack, one by one, to the Stack S2, then discard ' ('         Case '(':p Ush (S1, *p); Break;  Case ')': while(GetTop (S1)! ='(') {pop (s1, ch);                 Push (s2, ch); }pop (s1, ch);  Break; //in the case of the following operators, it is discussed in detail://1. If the stack top element of the current stack S1 is ' (', then the current operator is pressed directly into the stack S1;//2. Otherwise, the current operator is compared to the stack top element of the stack S1, and if the priority is larger than the top element of the stack, it is pressed directly into the stack S1,//Otherwise, the top element of the S1 stack pops up and presses into the stack S2 until the top of the stack operator has a lower precedence than the current operator and then presses the current operator into the stack S1         Case '+':         Case '-':             for(ch = getTop (S1); ch! ='#'; CH =GetTop (S1)) {                if(ch = ='(') Break; Elsepop (s1, ch); push (s2, ch); }push (S1,*P); length++; Break;  Case '*':         Case '/':             for(ch = getTop (S1); ch! ='#'&&ch! ='+'&&ch! ='-'; CH =GetTop (S1)) {                if(ch = ='(') Break; Elsepop (s1, ch); push (s2, ch); }push (S1,*P); length++; Break; default: Push (S2,*P); length++; }    }//if the stack s1 non-empty, the elements in the stack are popped and pressed into the stack S2     while(S1.Base!=s1.top && getTop (S1)! ='#') {pop (s1, ch);   Push (s2, ch); } //Finally, the Stack s2 output, in reverse order into a string;    Char*result; Result= (Char*)malloc(sizeof(Char) * (length +1)); Result+=length; * result =' /'; Result--;  for(; S2.Base!=s2.top; result--) {pop (s2, ch); * result =ch; }    ++result; returnresult;}voidMain () { while(1)    {        Charstr[ -]; inti;  for(i =0; i< -; i++) str[i]=' /'; printf ("Please enter an expression: \ n"); scanf ("%s", str); printf ("%s", Nibolan (str)); }}    

(1) First, the need to allocate 2 stacks, stack S1 for temporary storage operators (including a closing symbol), this operator in the stack to follow the higher the top of the stack of the principle of priority; Stack s2 is used for input inverse polish, for convenience, the stack S1 need to first put in a least-priority operator, The assumption here is ' # ';

(2) Start reading the character x one by one from the left end of the middle, and proceed sequentially to the following steps:

1. If x is the operand, the complete calculation is analyzed (here for convenience, with the letter instead of the number), the x is pressed directly into the stack S2;

2. If x is an operator, it is discussed in some cases:

If X is ' (', it is pressed directly into the stack S1;

If X is ') ', then the nearest ' (' operator from the top of the stack S1 stack, which is then pushed into the stack S2, then discarded ' (';

If X is an operator other than ' (' and ') ', then it is discussed in the following cases:

If the stack top element of the current stack S1 is ' ('), the x is pressed directly into the stack S1;

If the stack top element of the current stack S1 is not ' ('), the X is compared to the top element of the stack S1, and if the priority of X is greater than the stack S1 top operator priority, the x is pressed directly into the stack S1. No, the stack top operator of the stack S1 pops up and presses into the stack S2 until the stack top operator priority of the stack S1 is lower than (not equal to) the priority of X, or the stack top operator of the Stack S2 is ' (', at this point the X is pressed into the stack S1;

(3) after the completion (2), check whether the stack S1 is empty, if not empty, the stack of elements in turn popped up and pressed into the stack S2 (not including ' # ');

(4) After completing the above steps, the Stack S2 will be the inverse Polish output result. But stack S2 should do reverse processing, because the first character of the expression at the bottom of the stack;

Algorithmic---Conversion of single-letter variable expressions with subtraction and parentheses into inverse polish

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.