如何在Java中实现动态数组堆栈?

时间:2014-03-14 21:00:33

标签: java arrays dynamic stack

我需要修改一个类来创建一个动态数组栈。 此时我的代码看起来像这样:

public class DynamicArrayStack<E> implements Stack<E> {                                                                                                                                                                                                                                                                                                                                      

  private E[] elems;  //used to store the elements
  public static final int defaultIncrement = 25;
  private final int increment;

  private int top;  

  @SuppressWarnings( "unchecked" )  
  public DynamicArrayStack( int increment ) {
     this.increment = increment;

     elems = (E[]) new Object[ increment ];
     top = 0;

  }


  /** 
   * Constructor with no parameter that will initialize
   * the stack to have an array whose size is the value
   * of increment and memorise that value as the value
   * of increment.
   */  
  public void ArraySize() { }

  public boolean isEmpty() {
      return top == 0;
  }  

  public E peek() {
      return elems[ top-1 ];
  }  

  public E pop() {
      // save the top element
      E saved = elems[ --top ];
      // scrub the memory, then decrements top
      elems[ top ] = null;
      return saved;
  }  

  public void push( E elem ) {
      // stores the element at position top, then increments top
      elems[ top++ ] = elem;
  }  

  public String toString() {

      StringBuffer b;
      b = new StringBuffer( "DynamicArrayStack: {" );

      for ( int i=top-1; i>=0; i-- ) {
          if ( i!=top-1 ) {
              b.append( "," );
          }
          b.append( elems[ i ] );
      }

      b.append( "}" );

      return b.toString();
  }  
}

如何编辑第一个构造函数以将增量设置为堆栈的初始大小,以及在增大或减小数组大小时使用的相同值。我这样做的方法似乎太简单了。参数必须>当数组大小发生变化时,添加或删除固定数量的单元格。

第二个构造函数应该将堆栈设置为一个数组,其大小是increment的值。我一直在这里得到错误,因为我无法弄清楚如何做到这一点因为我认为这已经在第一个构造函数中设置了。数组的大小也作为增量值。

另外,如何让这个类能够改变堆栈的容量以及我应该将该代码放入哪个方法?

2 个答案:

答案 0 :(得分:2)

以下是简单 java代码来实现它:

1)基于堆栈:

  public class DynamicArrayStack {
    public static void main(String[] args) {

        DynamicStack dstack=new DynamicStack(2);
        System.out.println("--Pushing--");
        dstack.push(1);
        dstack.push(2);
        dstack.display();
        dstack.push(3);
        dstack.push(2);
        dstack.push(5);
        dstack.display();
        System.out.println("--Popping--");
        dstack.pop();
        dstack.pop();
        dstack.pop();
        dstack.display();

    }

}

class DynamicStack {
    private int top;
    private int capacity;
    private int[] array;

    public DynamicStack(int cap) {
        capacity = cap;
        array = new int[capacity];
        top = -1;
    }

    public void push(int data) {
        if (isFull()){
            expandArray();      //if array is full then increase its capacity
        }
        array[++top] = data;    //insert the data
    }

    public void expandArray() {
        int curr_size = top + 1;
        int[] new_array = new int[curr_size * 2];
        for(int i=0;i<curr_size;i++){
            new_array[i] = array[i];
        }
        array = new_array;              //refer to the new array 
        capacity = new_array.length;
    }

    public boolean isFull() {
        if (capacity == top+1)
            return true;
        else
            return false;
    }

    public int pop() {
        if (isEmpty()) {
            System.out.println("Stack is empty");
            return -1;
        } else {
            reduceSize();                 //function to check if size can be reduced
            return array[top--];
        }
    }

    public void reduceSize() {
        int curr_length = top+1;
        if (curr_length < capacity / 2) {
            int[] new_array = new int[capacity / 2];
            System.arraycopy(array, 0, new_array, 0, new_array.length);
            array = new_array;
            capacity = new_array.length;
        }
    }

    public boolean isEmpty() {
        if (top == -1)
            return true;
        else
            return false;
    }

    public void display() {
        for (int i = 0; i <= top; i++) {
            System.out.print(array[i] + "=>");
        }
        System.out.println();
        System.out.println("ARRAY SIZE:" + array.length);
    }

}

<强>输出:

- 推 -

1 =→2 =&GT;

ARRAY SIZE:2

1 =→2 =→3 =→2 =大于5 =&GT;

ARRAY SIZE:8

- 上托 -

1 =→2 =&GT;

ARRAY SIZE:4

2)基于链接列表:

   public class LinkListStack {
    public static void main(String[] args) {

        StackList stack = new StackList();
        System.out.println("--Pushing--");
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);
        stack.push(6);
        stack.display();
        System.out.println("--Popping--");
        stack.pop();
        stack.pop();
        stack.display();

    }
}

class Node {
    private int data;
    private Node next;

    public Node(int d) {
        data = d;
        next = null;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

}

class StackList {
    private Node top;
    private int length;

    public StackList() {
        length = 0;
        top = null;
    }

    public void push(int data) {
        Node temp = new Node(data);
        if (top == null) {
            top = temp;
        } else {
            temp.setNext(top);
            top = temp;
        }
        length++;
    }

    public int pop() {
        Node temp=top;
        int data = top.getData();
        top = top.getNext();
        temp=null;
        length--;
        return data;
    }

    public void display() {
        Node temp = top;
        if (isEmpty()) {
            System.out.println("Stack is empty");
        } else {
            while (temp != null) {
                System.out.print(temp.getData() + "=>");
                temp = temp.getNext();
            }
        }
        System.out.println();
    }

    public boolean isEmpty() {
        return (top == null);
    }

}

<强>输出:

- 推 -

6 =→5 =→4 =→3 =→2 =→1 =&GT;

- 上托 -

4 =→3 =→2 =→1 =&GT;

答案 1 :(得分:0)

默认构造函数

您的默认构造函数可以使用默认增量值调用您的其他构造函数。例如:

public DynamicArrayStack() {
    this(defaultIncrement);
}

扩展数组

扩展数组的正确位置在push方法中。尝试添加新元素时,可以检查数组是否足够大,如果没有,则创建一个新的更大的数组。例如,您可以执行以下操作:

@Override
public E push(final E elem) {
    // Check if we need to expand the array
    if (elems.length - 1 == top) {
        @SuppressWarnings("unchecked")
        final E[] newElems = (E[]) new Object[elems.length + increment];
        System.arraycopy(elems, 0, newElems, 0, elems.length);
        elems = newElems;
    }
    // stores the element at position top, then increments top
    elems[top++] = elem;
    return elem;
}

如果你想缩小数组,那么合理的地方就是pop()方法。您可能只想考虑在(top + (increment*2))<elems.length时减少长度,以避免在边界上重复复制数组。