stacks at the two ends of the array. The stacks willgrow in opposite direction.
ID: 3614777 • Letter: S
Question
stacks at the two ends of the array. The stacks willgrow in opposite direction. When
thetwo stacks collide and there is no more room in the array thestacks will over
flow. This problem is probably one of the easierproblems and targeted towards
exercising your array index manipulation skills.Implement push(x, i), pop(x, i),
isFull(), and isEmpty() operations, wherex is the data element andi is the stack
number
Explanation / Answer
Double stack code + small example. Notes: - isEmpty() is also given an argument to identify which stack, itmakes no sense without it. - This code uses asserts, make sure you find out what they do whenyou change some piece of code. Hint: pre-conditions andpost-conditions #include #include struct DoubleStack { int count[2]; int data[64]; DoubleStack(void); bool isFull(void)const; bool isEmpty(int stack)const; void push(int value, intstack); int pop(int stack); int getIndex(int index,int stack) const; }; DoubleStack::DoubleStack(void) { count[0] = 0; count[1] = 0; } bool DoubleStack::isFull(void) const { return(this->count[0] + this->count[1] == 64); } bool DoubleStack::isEmpty(int stack) const { assert(stack == 0 ||stack == 1); return(this->count[stack] == 0); } void DoubleStack::push(int value, int stack) { assert(stack == 0 ||stack == 1); assert(!this->isFull()); this->data[this->getIndex(this->count[stack]++, stack)] =value; } int DoubleStack::pop(int stack) { assert(stack == 0 ||stack == 1); assert(!this->isEmpty(stack)); returnthis->data[this->getIndex(--this->count[stack],stack)]; } int DoubleStack::getIndex(int index, int stack) const { assert(stack == 0 ||stack == 1); if (stack == 0) return index; else return 63 - index; } int main(void) { int i; DoubleStack stacks; for (i = 0; i < 64;i++) stacks.push(i, i & 1); if(!stacks.isFull()) std::coutRelated Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.