iven an array, push the values of the array until a -1 value is found or the sta
ID: 3854339 • Letter: I
Question
iven an array, push the values of the array until a -1 value is found or the stack is full - the -1 does not get pushed to the stack. After that, pop the values in the stack until an even value is found or the stack is empty - popping the even value. Then iterate until the stack is full or the inputArray is read completely.
Print the contents of the stack, from the top to bottom, using 0 for empty positions and a space to separate values. Example: 0 10 9 8 7 6
a) If inputArray={10, -1, 3, 2, 3, -1, 4, 5, 7, 8, 9, 10, 11} and maxSize=6 :
Explanation / Answer
import java.util.*;
public class StackOperation
{
public static void main(String[]arg)
{
Scanner in=new Scanner(System.in);
System.out.println("Enter number of elements:");
int num=in.nextInt();
int array[]= new int[num]; //array with number of elements
Stack stack= new Stack(); //instantiating stack object
System.out.println("Enter array elements:");
for(int i=0;i<array.length;i++)
{
array[i]=in.nextInt();
if(array[i]!=-1 )
{
stack.push(array[i]); //pushing array elements into stack
}
}
Iterator iter = stack.iterator();
while (iter.hasNext())
{
int val= (Integer)iter.next();
if(val%2==0)
{
stack.pop(); //poping even number of elements from the stack
}
}
System.out.println(stack);//displays stack elements after operations
System.out.println("Max Size="+stack.size()); //displays number of elements in the stack
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.