/**
* xxxxxx
* 3/28/19
* StackWithMAxNAive.java
* This program demonstrates the use of stacks.
*/
/**
* output:
* How many queries:
7
push 2
push 1
max
2
pop
max
2
*/
package module8project2;
import java.util.*;
import java.io.*;
/**
*
* @author Dilshad Haleem
* This program display the maximum number stored
* in a stack. It uses Collections.max method
* that took O(n) operations in oreder to find the maximum
* number on the stack, where n is the
* size of the Stack.
* <p>
* output:
*How many queries:
*3
*push 6
*push 2
*max
*6
*
*/
/**
*
* @author shottamon700
*
*/
public class StackWithMaxNaive{
static public void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
System.out.println("How many queries: ");
int queries = scan.nextInt();
//creating a stack to store integers
Stack<Integer> stack = new Stack<Integer>();
Stack<Integer> maxStack = new Stack<Integer>();
for (int qi = 0; qi < queries; ++qi) {
String operation = scan.next();
if ("push".equals(operation)) {
int value = scan.nextInt();
stack.push(value);
if(maxStack.isEmpty() || value > maxStack.peek() ) {
maxStack.push(value);
}
} else if ("pop".equals(operation)) {
if(maxStack.peek().equals(stack.peek()))
{
maxStack.pop();
}
stack.pop();
} else if ("max".equals(operation)) {
System.out.println(maxStack.peek());
}
}
}
}
Powered by TCPDF (www.tcpdf.org)