Sunday, 2 October 2011

4.1-4.5


4.1 Modified methods:
public Object pop()
{
    if(stack[stackTop] == null)
       System.out.println("Stack underflow, operation can not be completed");
    Object temp = stack[stackTop];
    stackTop--;
    return temp;
}//pop

public Object peekTop()
{
     if(stack[stackTop] == null)
       System.out.println("Stack underflow, operation can not be completed");
     return stack[stackTop];
}//peekTop

4.2
private boolean isFull()
{
     int count = 0;
     for(int i = 0; i<stack.length; i++)
     {
         if(stack[i] != null)
            count++;
        }
     if(count == max)
        return true;
     else return false;
} // returns true if full, otherwise returns false.

4.3 Modified push() method:
public void push(Object x)
{
    if(isFull()) {
      System.out.println("Stack overflow, operation can not be completed");
      return; }
    stackTop++;
    stack[stackTop]=x;
}//push

4.4 To be honest, I have no idea how to populate the ArrayStack in order to test it, and I'm coding out of pure logic, which so far seems to be working for me. I'll talk to you later about how to put in values for the Array in order to test it.

4.5
import java.util.ArrayList;
public class ArrayListStack implements Stack
{
    private ArrayList stack;
    private int stackTop;

public ArrayListStack()
{
    stack = new ArrayList();
    stackTop = -1;
}

public boolean isEmpty()
{
    return (stackTop==-1);
}//isEmpty

public void push(Object x)
{
    if(isFull()) {
      System.out.println("Stack overflow, operation can not be completed");
      return; }
    stackTop++;
    stack.get(stackTop) = x;
}//push

public Object pop()
{
    if(stack.get(stackTop) == null)
       System.out.println("Stack underflow, operation can not be completed");
    Object temp = stack.get(stackTop);
    stackTop--;
    return temp;
}//pop

public Object peekTop()
{
     if(stack.get(stackTop) == null)
       System.out.println("Stack underflow, operation can not be completed");
     return stack.get(stackTop);
}//peekTop

private boolean isFull()
{
     int count = 0;
     for(int i = 0; i<stack.length; i++)
     {
         if(stack.get(i) != null)
            count++;
        }
     if(count == max)
        return true;
     else return false;
} // returns true if full, otherwise returns false.

}//ArrayStack

No comments:

Post a Comment