Explore BrainMass
Share

Pop Function of Stack

This content was STOLEN 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[0];
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;
}

© BrainMass Inc. brainmass.com October 17, 2018, 12:47 am ad1c9bdddf
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
Similar Posting

queue and stack in C++

I need two separately programs from the same code.

1.) Modified the code so it has a Pop() function that makes the function of a Queue.

Example:

Input:

Enter Id: 1
Enter Name: Ana

Enter Id: 2
Enter Name: Carlos

Ouput:
(After a pop):

Id: 1
name: Ana

2.) Modified the code so it has a Pop() function that makes the function of a Stack.

Example:

Input:

Enter Id: 1
Enter Name: Ana

Enter Id: 2
Enter Name: Carlos

Ouput:
(After two pops):

Id: 2
Nombre: Carlos

Id: 1
Nombre: Ana

View Full Posting Details