【问题标题】:How can I implement a Dynamic Array Stack in Java?如何在 Java 中实现动态数组堆栈?
【发布时间】:2014-04-20 08:57:03
【问题描述】:

我需要修改一个类来创建一个动态数组堆栈。 此时我的代码如下所示:

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();
  }  
}

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

第二个构造函数应该将堆栈设置为一个数组,其大小是增量值。我在这里不断收到错误,因为我不知道该怎么做,因为我认为这已经在第一个构造函数中设置了。还将数组的大小作为增量值。

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

【问题讨论】:

  • 请同时提及进口。
  • 带有 javadoc 的方法不是构造函数 - 名称与类不匹配,它返回 void。如果increment &gt; 0,实际构造函数中的while 循环不会永远继续吗?目前尚不清楚它将如何退出。
  • 另外,您尝试实现的Stack 接口是什么。 java.util.Stack 是一个你需要extend 而不是implement 的类。
  • public DynamicArrayStack 是第一个构造函数,public void ArraySize() 是第二个。空白只是为了让课程继续编译,直到我得到正文。课程的主体应该是正确的(它是作为框架提供给我的)。这是我需要指导的其余部分。

标签: java arrays dynamic stack


【解决方案1】:

默认构造函数

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

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))&lt;elems.length 时考虑减少长度,以避免在边界上重复复制数组。

【讨论】:

    【解决方案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=>

    阵列大小:2

    1=>2=>3=>2=>5=>

    阵列大小:8

    --弹出--

    1=>2=>

    阵列大小: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=>

    --弹出--

    4=>3=>2=>1=>

    【讨论】:

      猜你喜欢
      • 2016-03-15
      • 1970-01-01
      • 2021-06-24
      • 2012-01-29
      • 2020-10-24
      • 2013-12-18
      • 2010-12-15
      • 2011-11-16
      • 2016-11-25
      相关资源
      最近更新 更多