18.2k views
0 votes
Suppose that you are asked to modify the Stack class to add a new operation max() that returns the current maximum of the stack comparable objects. Assume that pop and push operations are currently implemented using array a as follows, where item is a String and n is the size of the stack. Note: if x andy are objects of the same type, use x.compareTo(y) to compare the objects x and y public void push String item ) { [n++] = iten; } public String pop { return al--n]; } Implement the max operation in two ways, by writing a new method using array a (in 8.1), or updating push and pop methods to track max as the stack is changed (in 8.2). Q8.1 Implement method maxi 5 Points Write a method max() using Out) space and Oin) running time. public String max() {...} Enter your answer here Q8.2 Update push() and popo 5 Points Write a method max() using On) space and 011) run time. You may update the push and pop methods as needed public void push {...} public String pop() {...} public String max() {...}

User Dwoodard
by
3.6k points

1 Answer

3 votes

Answer:

Following are the code to the given points:

Step-by-step explanation:

For point 8.1:

public String max()//defining a method max

{

String maxVal=null;//defining a string variable that holds a value

for(int x=0;x<n;x++)

{

if(maxVal==null || a[i].compareTo(maxVal)>0)//defining if blok to comare the value

{

maxVal=a[i];//holding value in maxVal variable

}

}

return maxVal;//return maxVal variable value

}

For point 8.2:

public void push(String item)//defining a method push that accepts item value in a parameter

{

a[n]=item;//defining an array to hold item value

if(n==0 || item.compareTo(maxVals[n-1])>0)//use if to comare item value

{

maxVals[n]=item;//holding item value in maxVals variable

}

else

{

maxVals[n]=maxVals[n-1];//decreasing the maxVals value

}

n++;//incrementing n value

}

public String pop()//defining a method pop

{

return a[--n];//use return value

}

public String max()//defining a method max

{

return maxVals[n-1];//return max value

}

  • In the first point, the max method is declared that compares the string and returns its max value.
  • In the second point, the push, pop, and max method are declared that works with their respective names like insert, remove and find max and after that, they return its value.
User Anish Joseph
by
3.4k points