Write a segment of code (application level) to perform each of the following ope
ID: 3702480 • Letter: W
Question
Write a segment of code (application level) to perform each of the following operations. Assume myStack is an object of the class ArrayStack. You may call any of the public methods of ArrayStack. You may declare additional stack objects.
a) Set secondElement to the second element from the top of myStack , leaving myStack without its original top two elements.
b) Set bottom equal to the bottom element in myStack, leaving myStack empty.
c) Set bottom equal to the bottom equal to the bottom element in myStack, leaving myStack unchanged.
d) Print out the contents of myStack, leaving myStack unchanged.
Explanation / Answer
class ArrayStack
{
private Object[] stack;
private int topIndex = -1;
public ArrayStack()
{
stack = new Object[100];
}
public ArrayStack(int maxSize)
{
stack = new Object[maxSize];
}
public void push(Object item)throws Exception
{
if (!isFull())
{
topIndex++;
stack[topIndex] = item;
}
else
throw new Exception("Push attempted on a full stack.");
}
public Object pop()throws Exception
{
if (!isEmpty())
{
Object x=stack[topIndex];
stack[topIndex] = null;
topIndex--;
return x;
}
else
throw new Exception("Pop attempted on an empty stack.");
}
public Object top()throws Exception
{
Object topOfStack = null;
if (!isEmpty())
topOfStack = stack[topIndex];
else
throw new Exception("Top attempted on an empty stack.");
return topOfStack;
}
public void printStack(){
if(isEmpty()){
System.out.println("Stack is empty");
}
for(int i=topIndex;i>=0;i--){
System.out.println(stack[i].toString());
}
}
public boolean isEmpty()
{
if (topIndex == -1)
return true;
else
return false;
}
public boolean isFull()
{
if (topIndex == (stack.length - 1))
return true;
else
return false;
}
}
public class StackTest {
public static void main(String args[])throws Exception{
ArrayStack a=new ArrayStack();
a.push("4");
a.push("3");
a.push("2");
a.push("1");
a.printStack();
String first=a.pop().toString();
String secondElement=a.pop().toString();
System.out.println("secondElement is:"+ secondElement);
a.push(secondElement);
a.push(first);
System.out.println("a is:");
a.printStack();
ArrayStack b=new ArrayStack();
while(!a.isEmpty()){
b.push(a.pop());
}
String bottom=b.pop().toString();
System.out.println("bottom is:"+ bottom);
a.push(bottom);
while(!b.isEmpty()){
a.push(b.pop());
}
System.out.println("a is:");
a.printStack();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.