Computer Science 261

Exercise set #5

Due:  Thursday, Oct. 21

Two parts. As with exercise #4, writing the routines will be useful review for the exam Friday.

 

Consider the following class definition and main routine:

 

#include <iostream.h>

const int StackSize = 15;

class IntStack{

public:

//	Constructor / destructor

	IntStack()
	{
		theStack = new int[StackSize];
		TOS = 0;
	}

	~IntStack()
	{
		delete [] theStack;
		TOS = 0;
	}
//
//	You will need to change the constructor and destructor
//	when you change this to a linked list implementation.

//   Accessor functions

	void Push(int theArgument);
	int Pop();

	bool IsEmpty();
	bool IsFull();

private:
	int *theStack;
	int TOS;
};

int main()
//
//	A simple calculator.  Uses cin.get and cin.putback
//
{
	IntStack MyStack;
	int temp1, temp2;
	char ch;

	cout << endl << "Simple RPN calculator.  End with ';'" << endl;
	cin.get(ch);	// Get the first character
	while ((ch == ' ') || (ch == '\n'))  // Skip over "noise" (blanks and
										// newlines
		cin.get(ch);
	while (ch != ';')
	{
	switch (ch) {
		case '+' : {
			temp1 = MyStack.Pop();
			temp2 = MyStack.Pop();
			MyStack.Push(temp2 + temp1);
			break;
				   }
		case '-' : {
			temp1 = MyStack.Pop();
			temp2 = MyStack.Pop();
			MyStack.Push(temp2 - temp1);
			break;
				   }
		case '*' : {
			temp1 = MyStack.Pop();
			temp2 = MyStack.Pop();
			MyStack.Push(temp2 * temp1);
			break;
				   }
		case '/' : {
			temp1 = MyStack.Pop();
			temp2 = MyStack.Pop();
			MyStack.Push(temp2 / temp1);
			break;
				   }
		default : {  // assume that ch is the start of an integer number
			cin.putback(ch);
			cin >> temp1;
			cout << "\nPushing value " << temp1 << endl;
			MyStack.Push(temp1);
			break;
				   }
	}	// end of switch
	cin.get(ch);  // Get the next character
	while ((ch == ' ') || (ch == '\n'))  //Skip over noise.  This could be written
									// as a 'GetNextCharacter' routine.
		cin.get(ch);
	}
	cout << "\nDone!  The result of your calculations is : ";
	cout << MyStack.Pop();
	cout << endl;

	return 0;
}

 

  1. Incorporate the above into a program called stack01.cpp which implements the stack ADT using an array. In this case, the constructor and destructor have already been written for you.
  2. Incorporate the above into a program stack02.cpp which implements the stack ADT using a linked list. You will need to re-write the constructor and destructor.

In both cases, test your program using the main program provided (a simple calculator using the integer stack. Take particular note of the use of cin.get and cin.putback.