(COMP2012)[2011](s)final_=9eu_^_64001.pdf

# Implementing stacks and queues using inheritance and

• Test Prep
• 8

This preview shows pages 3–6. Sign up to view the full content.

3. Implementing Stacks and Queues Using Inheritance and Polymorphism (23 points) (a) (7 points) Solution: MyArray::MyArray():size(0), data(0){ } MyArray::~MyArray() { delete[] data; } voidMyArray::push(int elem){ int* newData=newint[size+1]; // allocate a larger array for (int i=0; i<size; i++) newData[i] = data[i];// copy elements over newData[size]=elem; if(data) delete[] data;// release the old memory data = newData; size+=1; } (b) (6 points) Solution: class MyStack : public MyArray{ public: int pop() { if(size==0) return -1; // pop error int* newData=newint[size-1]; //allocate new array of smaller size int value = data[size-1]; size-=1; for(int i=0;i<size;i++) { newData[i]=data[i]; } delete[] data; data=newData; return value; } }; (COMP2012)[2011](s)final~=9eu_^_64001.pdf downloaded by xjiae from at 2018-03-13 17:27:49. Academic use within HKUST only.

This preview has intentionally blurred sections. Sign up to view the full version.

Page 4 (c) (6 points) Soution: class MyQueue : public MyArray{ public: intpop() { if(size==0) return -1; int* newData=newint[size-1]; int value = data[0]; size-=1; for(int i=0; i < size; i++) { newData[i] = data[i+1]; } delete[] data; data=newData; return value; } }; (d) (4 points) Solution: Void printAndClear(MyArray* stkQ){ int value = stkQ->pop(); while (value!=-1){ cout << value << " "; value = stkQ->pop(); } } (COMP2012)[2011](s)final~=9eu_^_64001.pdf downloaded by xjiae from at 2018-03-13 17:27:49. Academic use within HKUST only.
Page 5 4. List Implementation Using Template and Overloading (25 points) (a) (6 points) Solution : In List class, add: List<T> operator+(T) const; template<typename T>

This preview has intentionally blurred sections. Sign up to view the full version.

This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

### What students are saying

• As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

Kiran Temple University Fox School of Business ‘17, Course Hero Intern

• I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

Dana University of Pennsylvania ‘17, Course Hero Intern

• The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

Jill Tulane University ‘16, Course Hero Intern