Question

Design a stack class by importing the available java.util.Stack to have the following features: push(x) --...

Design a stack class by importing the available java.util.Stack to have the following features:

  • push(x) -- push element x onto stack, where x is anywhere between Integer.MIN_VALUE and Integer.MAX_VALUE.
  • pop() -- remove the element on top of the stack.
  • top() -- get the top element.
  • getMax() -- retrieve the max element in the stack in constant time (i.e., O(1)).

Your code should have the following shape and form, all in one .java file. Note the styling and documentation API already included for the target class, MaxStack:

import java.util.Stack;
public class HomeworkAssignment1_1 {   
    public static void main(String[] args) {
       // Your main() is not graded so you can
       // have any implementation in this area
       MaxStack obj = new MaxStack();
       obj.push(12);
       obj.push(1);
       obj.push(-12);
       obj.pop();
       System.out.println(obj.top());
       System.out.println(obj.getMax());
       // etc.
   }
}
/**

* The MaxStack program implements a Stack class with the following features:
* push(x) -- push element x onto stack
* pop() -- remove the element on top of the stack
* top() -- get the top element.
* getMax() -- retrieve the max element in the stack in constant time (i.e., O(1)

*/
class MaxStack {
   // Initialize your data structure in constructor
   // or here; choice is yours.

   public MaxStack() { // YOUR CODE HERE }

public void push(int x) { // YOUR CODE HERE }
   public void pop() { // YOUR CODE HERE }
   public int top() { // YOUR CODE HERE }
   public int getMax() { // YOUR CODE HERE }
}

EXAMPLES

MaxStack maxStack = new MaxStack();

maxStack.push(-2);

maxStack.push(0);

maxStack.push(-3);

maxStack.getMax(); // returns 0

maxStack.pop();

maxStack.top(); // returns 0

maxStack.getMax(); // returns 0

CONSTRAINTS AND ASSUMPTIONS

  • For this problem you are ONLY allowed to use Java's reference class Stack (Links to an external site.). Failure to do so will receive 5 points off.
  • MaxStack does not mean elements have to be ordered in increasing or decreasing values in the Stack.

HINTS

  • You solution should persist a global max value while maintaining the ability to transact on a java.util.Stack instance wrapped in your MaxStack class.
  • When implementing the MaxStack methods, you will have to invoke your Java stack instance's comparable methods (naming convention may be different).
0 0
Add a comment Improve this question Transcribed image text
Answer #1

//name the file HomeworkAssignment_1

import java.util.Stack;

public class HomeworkAssignment1_1 {

static class MaxStack

{

Stack<Integer> s = new Stack<Integer>();

int maxEle;

void getMax()

{

if (s.empty())

System.out.print("Stack is empty\n");

// variable maxEle stores the maximum element

// in the stack.

else

System.out.println(maxEle);

}

// Prints top element of MyStack

void top()

{

if (s.empty())

{

System.out.println("Stack is empty ");

return;

}

int t = s.peek(); // Top element.

// If t < maxEle means maxEle stores

// value of t.

if(t > maxEle)

System.out.println(maxEle);

else

System.out.println(t);

}

// Remove the top element from MyStack

void pop()

{

if (s.empty())

{

System.out.println("Stack is empty");

return;

}

int t = s.peek();

s.pop();

// Maximum will change as the maximum element

// of the stack is being removed.

if (t > maxEle)

{

maxEle = 2 * maxEle - t;

}

}

// Removes top element from MyStack

void push(int x)

{

// Insert new number into the stack

if (s.empty())

{

maxEle = x;

s.push(x);

return;

}

// If new number is less than maxEle

if (x > maxEle)

{

s.push(2 * x - maxEle);

maxEle = x;

}

else

s.push(x);

}

};

public static void main(String[] args) {

// have any implementation in this area

MaxStack maxStack = new MaxStack();

maxStack.push(-2);

maxStack.push(0);

maxStack.push(-3);

maxStack.getMax(); // returns 0

maxStack.pop();

maxStack.top(); // returns 0

}

}


Add a comment
Answer #2

To implement the MaxStack class with the specified features, we need to use the Java Stack class and maintain a global max value while performing the push, pop, top, and getMax operations.

Here's the complete MaxStack class implementation:

javaCopy codeimport java.util.Stack;/**
 * The MaxStack program implements a Stack class with the following features:
 * push(x) -- push element x onto stack
 * pop() -- remove the element on top of the stack
 * top() -- get the top element.
 * getMax() -- retrieve the max element in the stack in constant time (i.e., O(1))
 */class MaxStack {    private Stack<Integer> stack;    private int max;    public MaxStack() {
        stack = new Stack<>();
        max = Integer.MIN_VALUE;
    }    public void push(int x) {        if (x > max) {
            stack.push(2 * x - max); // Store an encoded value to track the maximum element
            max = x;
        } else {
            stack.push(x);
        }
    }    public void pop() {        if (stack.isEmpty()) {            return;
        }        int popped = stack.pop();        if (popped > max) {
            max = 2 * max - popped; // Decode the stored encoded value to get the previous maximum
        }
    }    public int top() {        if (stack.isEmpty()) {            return -1; // Return a default value indicating an empty stack
        }        int peeked = stack.peek();        if (peeked > max) {            return max; // Return the maximum value instead of the encoded value
        } else {            return peeked;
        }
    }    public int getMax() {        return max;
    }
}public class HomeworkAssignment1_1 {    public static void main(String[] args) {        MaxStack obj = new MaxStack();
        obj.push(12);
        obj.push(1);
        obj.push(-12);
        obj.pop();
        System.out.println(obj.top()); // Output: 1
        System.out.println(obj.getMax()); // Output: 12
    }
}

Explanation:

  • The MaxStack class uses a Java Stack to store the elements.

  • We maintain a global variable max to keep track of the maximum element in the stack.

  • In the push method, we compare the new element with the current maximum. If the new element is greater than the current maximum, we store an encoded value on the stack and update the maximum. Otherwise, we directly push the new element onto the stack.

  • In the pop method, we check the top element of the stack. If it is greater than the current maximum, we decode the stored encoded value to get the previous maximum.

  • In the top method, we check the top element of the stack. If it is greater than the current maximum, we return the current maximum as it is the actual top element. Otherwise, we return the element as it is.

  • The getMax method simply returns the current maximum value.

This implementation allows us to perform the getMax operation in constant time (O(1)) without sacrificing the efficiency of other operations.


answered by: Hydra Master
Add a comment
Know the answer?
Add Answer to:
Design a stack class by importing the available java.util.Stack to have the following features: push(x) --...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Same problem as Problem 1 however you will implement the opposite of a MaxStack, namely MinStack....

    Same problem as Problem 1 however you will implement the opposite of a MaxStack, namely MinStack. Design a stack class by importing the available java.util.Stack to have the following features: push(x) -- push element x onto stack, where x is anywhere between Integer.MIN_VALUE and Integer.MAX_VALUE. pop() -- remove the element on top of the stack. top() -- get the top element. getMin() -- retrieve the min element in the stack in constant time (i.e., O(1)). Your code should have the...

  • template <class T> class Stack { public: /** clear * Method to clear out or empty any items on stack, * put stack back to empty state. * Postcondition: Stack is empty. */ virtual void clear() =...

    template <class T> class Stack { public: /** clear * Method to clear out or empty any items on stack, * put stack back to empty state. * Postcondition: Stack is empty. */ virtual void clear() = 0; /** isEmpty * Function to determine whether the stack is empty. Needed * because it is undefined to pop from empty stack. This * function will not change the state of the stack (const). * * @returns bool true if stack is...

  • NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT...

    NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT WOULD CAUSE THE HW1.java TO PRINT THE RIGHT DATA.!!! The LinkedList class implements both the List interface and the Stack interface, but several methods (listed below) are missing bodies. Write the code so it works correctly. You should submit one file, LinkedList.java. Do not change the interfaces. Do not change the public method headers. Do not rename the LinkedList class. None of your methods...

  • JAVA PROGRAM Design a stack that supports push, pop, top, and retrieving the minimum element in...

    JAVA PROGRAM Design a stack that supports push, pop, top, and retrieving the minimum element in constant time. • push(x) -- Push element x onto stack. • pop() -- Removes the element on top of the stack. • top() -- Get the top element. • getMin() -- Retrieve the minimum element in the stack. Example 1: Input ["MinStack", "push", "push","push", "getMin","pop","top", "getMin"] [1], [-2], [0], [-3],[1,1],[1, [1] Output [null, null, null,null,-3, null,0,-2] Explanation MinStack minStack = new MinStack(); minStack.push(-2); minStack.push(0);...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an ...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private static...

  • Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make...

    Now, your objective is to rewrite the same Stack class with a Generic ArrayList and make the entire class support using Generic types. You should be able to create a Stack of any primitive wrapper class, and show us that your Generic Stack implementation (push, pop, search, display, etc.) works with: • Character (Stack) • Integer (Stack) • Float (Stack • Double (Stack) • String (Stack) You can create these Stack objects in main() and perform operations on them to...

  • Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored...

    Java. Must not use Java API java.util.Stack /** A class of stacks whose entries are stored in an array. Implement all methods in ArrayStack class using resizable array strategy, i.e. usedoubleArray() Must throw StackException during exception events in methods:    peek(), pop(), ArrayStack(int initialCapacity) Do not change or add data fields Do not add new methods */ import java.util.Arrays; public class Arraystack«Т> implements Stack!nterface«T> private TI stack;// Array of stack entries private int topIndex; /7 Index of top entry private...

  • I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and...

    I need to implement raw array Stack for create empty stack, isEmpty, isFull, push, pop, and size using below pseudo code. I need two classes with stack pseudo code implementation and the main method to demonstrate the correct working of each operation. pseudo code StackADT (using raw array) class StackADT { int top int items[] int max StackADT(int n) Initialize array to n capacity top = 0 max = n boolean isEmpty() if array has no elements return true else...

  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
Active Questions
ADVERTISEMENT