Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Please write the algorithm and use java to show this. Please write the algorithm

ID: 3755387 • Letter: P

Question

Please write the algorithm and use java to show this.

Please write the algorithm and use java to show this.Please write the algorithm and use java to show this.

Please write the algorithm and use java to show this.

ALGORITHM Propose a data structure that supports the stack operations PUSH, POP, and a third operation FIND MIN which returns the smallest element in the stack (does not delete the element). All three operations should run in O(1) worst case time. Write algorithms for the three operations Provide an example (with actual numbers) to show how each algorithm works.

Explanation / Answer

import java.util.Stack; //import stack

class StackOperation extends Stack<Integer> {  

Stack<Integer> getMin = new Stack<>(); //create a stack getMin to store minmum value

//to push an element

void push(int a) {

if (isEmpty() == true) {

super.push(a);//main stack

getMin.push(a);//min vlue stack

} else {

super.push(a);

int b = getMin.pop(); //update value of minimum

getMin.push(b);

if (a < b)

getMin.push(a);

else

getMin.push(b);

}

}

//to pop an element

public Integer pop() {

int a = super.pop();

getMin.pop();

return a;

}

//to find min

int findMin() {

int a = getMin.pop();

getMin.push(a);

return a;

}

// main class

public static void main(String[] args) {

StackOperation stack = new StackOperation(); //create a object

stack.push(1); //examples first push 5

stack.push(6); //push 6

stack.push(2);//push 2

stack.push(1);//push 1

stack.pop(); //pop 1

System.out.println(stack.findMin()); //find min which is 2

}

}