Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Data Structures CSCI 132, Spring 2016 Notes 6 Applications using Stacks.

Similar presentations


Presentation on theme: "1 Data Structures CSCI 132, Spring 2016 Notes 6 Applications using Stacks."— Presentation transcript:

1 1 Data Structures CSCI 132, Spring 2016 Notes 6 Applications using Stacks

2 2 Recall the Stack class typedef int Stack_entry; const int maxstack =10 ;//small value for testing class Stack { public: Stack(); bool empty()const; Error_code pop(); Error_code top(Stack_entry &item)const; Error_code push(const Stack_entry &item); private: int count ; Stack_entry entry [maxstack ]; };

3 3 Implementing push( ) Error_code Stack ::push(const Stack_entry &item) { //we will implement this method in class }

4 4 Implementing pop( ) Error_code Stack ::pop() { //we will implement this method in class }

5 5 Implementing top( ) Error_code Stack ::top(Stack_entry &item) const { //implement top( ) }

6 6 Implementing empty( ) and Stack( ) bool Stack ::empty( )const { //implement empty( ) } Stack ::Stack() {//implement Stack( ) }

7 7 Reverse Polish Calculator: A stack application Numbers are pushed onto a stack as they are entered. An arithmetic operation is done on the top two items in the stack, which are popped off the stack. The result is pushed onto the stack. Reverse polish arithmetic allows you to do any arithmetic calculation without using parentheses. For example, the computation (6 + 2) is written as 6 2 + in reverse polish notation.

8 8 Example Regular notation: (6 + 2) / (7 - 3) Reverse Polish: 6 2 + 7 3 - /

9 9 Rules for Calculator use User enters a command: ?, =, +, -, *, or / ? means the next entry is a number. = means print the result (top of stack). All others mean perform the given arithmetic operation.

10 The main calculator program #include //stack class from the Standard Template Library int main (void) { char command ; Stack stored_numbers; cout <<"Enter a command: "; cin >> command; command = tolower(command); while (command != 'q'){ if (command == '?'||command == '='||command == '+' || command == '-'||command == '*'||command == '/' ) { do_command(command, stored_numbers); } else { cout <<"Please enter a valid command:"<<endl <<"[?]push to stack [=]print top "<<endl <<"[+][-][*][/]are arithmetic operations "<<endl <<"[Q ]uit."<<endl; } cout << "Enter a command: "; cin >> command; command = tolower(command); } }

11 11 Processing commands void do_command(char command,Stack &numbers) { double p,q ; switch (command){ case '?': break; case '=': break;

12 12 More number processing case '+': break; //Add options for further user commands. } //end switch } //end do_command


Download ppt "1 Data Structures CSCI 132, Spring 2016 Notes 6 Applications using Stacks."

Similar presentations


Ads by Google