以相反的顺序打印数组元素

时间:2015-11-17 12:40:19

标签: java arrays stack

package SimpleArrayStackofchars;

    public class SimpleArrayStackofchars implements Stack
    {
    protected int capacity;     // The actual capacity of the stack array 
    public static final int CAPACITY = 2;   // default array capacity
    protected Object S[];       // Generic array used to implement the stack 
    protected int top = -1; // index for the top of the stack (-1 = empty stack)
    public SimpleArrayStackofchars() 
    {
        this(CAPACITY); // default capacity
    }
    public SimpleArrayStackofchars(int cap)
    {
        capacity = cap;
        S = new Object[capacity];
    }
    public int size() 
    {
            return (top + 1);
    }
    public boolean isEmpty() 
    {
        return (top == -1);
    }
        public void push(Object element) throws FullStackException 
    {
        if(size() == capacity) 
        {
      //throw new FullStackException
            ("Stack is full. Stack size max is "+ capacity);
     /*can replace previous line with code to double stack size
    */
                doubleArray();
        }
            S[++top] = element;
    }
    public Object top() throws EmptyStackException 
    {
        if (isEmpty())
        throw new EmptyStackException("Stack is empty.");
        return S[top];
    }
    public Object pop() throws EmptyStackException 
    {
        Object element;
        if (isEmpty())
      throw new EmptyStackException("Stack is empty.");
        element = S[top];
        S[top--] = null; // dereference S[top] for garbage collection.
        return element;
    }
    private void doubleArray( )
    {
        Object [ ] newArray;
    System.out.println("Stack is full (max size was "+capacity+"). Increasing to "+(2*capacity));
      //double variable capacity
        capacity = 2*capacity;
        newArray = new Object[ capacity ];
        for( int i = 0; i < S.length; i++ )
        newArray[ i ] = S[ i ];
        S = newArray;
    }
    public static void main(String[] args) 
    {
            Stack S = new SimpleArrayStackofchars();
            S.push("1");
            S.push("2");
            S.push("3");
            S.push("4");
            S.push("5");
            S.push("6");

            while (!S.isEmpty()) 
        {
                System.out.println(S.pop());
            }
        }
    }

所以我上面有这个代码,当我运行它时,它打印输出。但是,我还有另一个问题,我不明白该怎么做。

这是问题:重新编写main方法,以便调用另一个名为reverseUsingPop的方法,该方法将使用一个字符数组并使用pop方法以相反的顺序打印数组元素。

1 个答案:

答案 0 :(得分:0)

您已经创建了方法,因此您知道如何执行此操作。您可以创建另一个名为reverseUsingPop(char [] characters)的方法。并在此处执行循环以打印它们。

从查看代码看起来你应该已经看到了所有这些。因此,从您的main方法中,您可以调用该方法。