Explore BrainMass
Share

# Pop Function of Stack

This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

Modify the pop() function of Stack so that it uses recursion.

/**
* pop - pops the top node from the stack. Return -1 if the stack is
* empty.
*/
int Stack::pop()
{
int pop = -1;

// Create a temporary set of node to hold the new stack
int *tmp_nodes = new int[size];
memset(tmp_nodes, 0, sizeof(int) * size);

// If the stack is not empty, pop the first node and copy the
// remaining elements of the nodes into the tmp_nodes
if (nodes && !isEmpty())
{
pop = nodes;
for (int i=0; i < size; i++)
{
tmp_nodes[i] = nodes[i+1];
}
curpos--;
}

// Update the stack
memset(nodes, 0, sizeof(int) * size);
memcpy(nodes, tmp_nodes, sizeof(int) * size);

delete [] tmp_nodes;

return pop;
}

https://brainmass.com/computer-science/algorithms/pop-function-stack-310465

#### Solution Preview

Since question just asks to use recursion in pop function, and it does not clearly mention whether pop function itself has to be made recursive or recursion has to be used in part of it. This solution assumes the latter.

/**
* recursive_copy_into_temporary_stack
*/

void ...

#### Solution Summary

Since question just asks to use recursion in pop function, and it does not clearly mention whether pop function itself has to be made recursive or recursion has to be used in part of it. This solution assumes the latter and converts the for-loop copying in it to recursive copying.

\$2.19