C ++ Data Structure Learning stack Application

Source: Internet
Author: User

InC ++ Data StructureMedium,StackStack is widely used. The biggest purpose of stack is to solve the Backtracking problem, which also involves eliminating recursion. When you use stack to solve the Backtracking problem, you rarely think of recursion, such as the maze. In addition, the habits of people are also preemptible, such as tree traversal. From the day of study, this is a recursive algorithm. Although the book also teaches how to implement with stacks, the first thing you think of is recursion. Of course, if the language itself does not support recursion (such as BASIC), the stack is the only choice-as if the current advanced language supports recursion.

The following is the definition and implementation of expression classes. expressions can be infix or suffix, and are distinguished by type in the data field of the header node, due to the assignment function of a single-chain table, I did not copy the content of the header node when I wrote it. Therefore, if I assigned a value between two expressions, the information stored in the header node would be lost. You can rewrite the value assignment function of a single-chain table to solve this problem, or you can assign values between two expressions at all.

 
 
  1. # Ifndef Expression_H 
  2. # Define Expression_H 
  3. # Include "List. h" 
  4. # Include "Stack. h" 
  5. # Define INFIX 0 
  6. # Define POSTFIX 1 
  7. # Define OPND 4 
  8. # Define OPTR 8 
  9.  
  10. Template<ClassType>ClassExpNode
  11. {
  12.  Public:
  13. IntType;
  14. Union{Type opnd;CharOptr ;};
  15. ExpNode (): type (INFIX), optr ('='){}
  16. ExpNode (Type opnd): type (OPND), opnd (opnd ){}
  17. ExpNode (CharOptr): type (OPTR), optr (optr ){}
  18. };
  19.  
  20. Template<ClassType>ClassExpression: List >
  21. {
  22.  Public:
  23. VoidInput ()
  24. {
  25. MakeEmpty (); Get ()-> type = INFIX;
  26. Cout <endl <"Input expression, ending with ="<Endl;
  27. Type opnd;CharOptr ='';
  28.  While(Optr! ='=')
  29. {
  30. Cin> opnd;
  31. If(Opnd! = 0)
  32. {
  33. ExpNode Newopnd (opnd );
  34. LastInsert (newopnd );
  35. }
  36. Cin> optr;
  37. ExpNode Newoptr (optr );
  38. LastInsert (newoptr );
  39. }
  40. }
  41. VoidPrint ()
  42. {
  43. First ();
  44. Cout <endl;
  45.  For(ExpNode * P = Next (); p! = NULL; p = Next ())
  46. {
  47. Switch(P-> type)
  48. {
  49.  CaseOPND:
  50. Cout <p-> opnd;Break;
  51.  CaseOPTR:
  52. Cout <p-> optr;Break;
  53.  Default:Break;
  54. }
  55. Cout <'';
  56. }
  57. Cout <endl;
  58. }
  59. Expression & Postfix ()// Convert an infix expression to a suffix expression 
  60. {
  61. First ();
  62.  If(Get ()-> type = POSTFIX)Return*This;
  63. Stack <Char> S; s. Push ('=');
  64. Expression temp;
  65. ExpNode * P = Next ();
  66.  While(P! = NULL)
  67. {
  68. Switch(P-> type)
  69. {
  70.  CaseOPND:
  71. Temp. LastInsert (* p); p = Next ();Break;
  72.  CaseOPTR:
  73.  While(Isp (s. GetTop ()> icp (p-> optr ))
  74. {
  75. ExpNode Newoptr (s. Pop ());
  76. Temp. LastInsert (newoptr );
  77. }
  78.  If(Isp (s. GetTop () = icp (p-> optr ))
  79. {
  80. S. Pop (); p = Next ();Break;
  81. }
  82. S. Push (p-> optr); p = Next ();Break;
  83.  Default:Break;
  84. }
  85. }
  86. *This= Temp;
  87. PGetFirst ()-> data. type = POSTFIX;
  88.  Return*This;
  89. }
  90.  
  91. Type Calculate ()
  92. {
  93. Expression temp = *This;
  94.  If(PGetFirst ()-> data. type! = POSTFIX) temp. Postfix ();
  95. Stack S; Type left, right;
  96.  For(ExpNode * P = temp. Next (); p! = NULL; p = temp. Next ())
  97. {
  98. Switch(P-> type)
  99. {
  100.  CaseOPND:
  101. S. Push (p-> opnd );Break;
  102.  CaseOPTR:
  103. Right = s. Pop (); left = s. Pop ();
  104. Switch(P-> optr)
  105. {
  106.  Case '+': S. Push (left + right );Break;
  107.  Case '-': S. Push (left-right );Break;
  108.  Case '*': S. Push (left * right );Break;
  109.  Case '/':If(Right! = 0) s. Push (left/right );Else Return0;Break;
  110. // Case '%': if (right! = 0) s. Push (left % right); else return 0; break; 
  111. // Case '^': s. Push (Power (left, right); break; 
  112.  Default:Break;
  113. }
  114. Default:Break;
  115. }
  116. }
  117. ReturnS. Pop ();
  118. }
  119.  
  120. Private:
  121.  IntIsp (CharOptr)
  122. {
  123. Switch(Optr)
  124. {
  125.  Case '=':Return0;
  126.  Case '(':Return1;
  127.  Case '^':Return7;
  128.  Case '*':Return5;
  129.  Case '/':Return5;
  130.  Case '%':Return5;
  131.  Case '+':Return3;
  132.  Case '-':Return3;
  133.  Case ')':Return8;
  134.  Default:Return0;
  135. }
  136. }
  137.  
  138.  IntIcp (CharOptr)
  139. {
  140. Switch(Optr)
  141. {
  142.  Case '=':Return0;
  143.  Case '(':Return8;
  144.  Case '^':Return6;
  145.  Case '*':Return4;
  146.  Case '/':Return4;
  147.  Case '%':Return4;
  148.  Case '+':Return2;
  149.  Case '-':Return2;
  150.  Case ')':Return1;
  151.  Default:Return0;
  152. }
  153. }
  154. };
  155.  
  156. # Endif 

Notes

1. The expressions are stored in a single-chain table. You can see that this linked list contains both operands and operators, if you have read another article about how to link different types of objects to the C ++ linked list, the method here is also a supplement to that article.

2. When an expression is input, the original content is cleared and must be input according to the infix. If you take a closer look at the infix expression, you will find that, except for the brackets, the expression structure is "operand", "operator", "operand ",...... "Operator (=)", in order to unify this rule, and to make the input function simpler, it is required that brackets enter "0 (", ") 0" in this way, "0" cannot appear in the expression as the operand. Because I have not added a fault-tolerant statement to the input function, once an error is entered, the program will be "dead.

3. The process of expression value evaluation is to first convert the expression into a suffix and then use a suffix to represent the value. Because the original book explains these two algorithms, and these two algorithms can be used to complete the evaluation of the infix expression, so I did not write the direct evaluation algorithm of the infix expression.

4. The two lines commented out by Calculate (). "%" is only valid for integer expressions. The "^" Power () function is not completed.

5. isp () and icp () return values. I 'd like to say a few more words. '=' (Expression start and end signs) has the lowest priority outside the stack. '('The maximum outside the stack, the lowest in the stack. ')' The minimum number of times outside the stack is not pushed to the stack. '^' The number of times in the stack is the highest, and the number of times out of the stack is lower than that in the stack. '× Memory %' is lower than '^' in the stack, and the out-of-stack is lower than in the stack. '+-' Stack is lower than '×' stack, and stack is lower than stack. In this way, there are nine priorities.

  1. Analysis on C ++ stack usage
  2. The database uses the C ++ Data Structure
  3. Programmers must read the summary of c ++ pen questions
  4. Common c ++ programming tools
  5. C ++ Data Structure Learning stack and queue

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.