【问题标题】:Creating a Stack class with Arrays in Java在 Java 中创建带有数组的 Stack 类
【发布时间】:2015-03-31 19:10:30
【问题描述】:

我正在尝试在 Java 中创建一个堆栈,该堆栈使用数组来实现。下面是我自定义的栈类中的pop()方法

public E pop()
    {
        if(data.length == 0)
        {
            throw new EmptyStackException();
        }
        E poppedObject = data[0];
        for(int i = 0; i < data.length-1; i++) //Moving all the elements one closer to top
        {
            data[i] = data[i+1];
        }
        return poppedObject;
    }

当所有数据都从堆栈中弹出并且您尝试从中弹出一些内容时,应该抛出 EmptyStackException。但是, data.length 不会随着对象的弹出而改变。如果不能用 data.length 判断,pop 方法应该如何判断堆栈是否为空?

【问题讨论】:

  • 假设你有一个 kitkat,里面有 4 个巧克力棒。当你吃一个kit kat bar时,包装的大小会改变还是kit kat bar的数量会改变?

标签: java arrays stack


【解决方案1】:

设置一个计数器来告诉您数组中的元素数量。 Array.length 单独会告诉您堆栈的容量,而不是堆栈中的元素数量。对于这个例子,count 是我的计数器

public E pop() throws EmptyStackException {
    if(count <= 0) {
        throw new EmptyStackException();
    }
    E poppedObject = data[0];
    for(int i = 0; i < count; i++) { //Moving all the elements one closer to top
        data[i] = data[i+1];
    }
    count--;
    return poppedObject;
}

还请注意,如果您正确实现堆栈,堆栈将自下而上增长,因此无需将所有元素移动到更靠近顶部的位置。所以如果你这样做,pop 方法应该是:

public E pop() throws EmptyStackException {
    if(count == 0) {
        throw new EmptyStackException();
    } 
    return data[--count];
}

【讨论】:

    【解决方案2】:

    我建议你看看 Stack 类是如何实现的。它也使用一个数组,但是有一个 size 字段来保存堆栈的大小。

    仅当大小增长大于数组长度时,数组才需要更改。

    来自 Stack.pop();

    public synchronized E pop() {
        E       obj;
        int     len = size();
    
        obj = peek();
        removeElementAt(len - 1);
    
        return obj;
    }
    

    顺便说一句,在堆栈中,您永远不需要重新排列元素。你应该从最后添加/删除。

    在你的情况下,你可以写。

    public int size() { return size; }
    
    public void push(E e) {
        if (size == data.length) growArray();
        data[size++] = e;
    }
    
    public E pop() {
        if (size == 0) throw new EmptyStackException();
        return data[--size];
    }
    

    【讨论】:

      【解决方案3】:

      以下是用户定义的 Stack 代码如何在内部实现。

      class UserDefinedStack< E> {
      
          private static int defaultCapacity = 5;
          private E[] stack = null;
          int top = -1;
      
          /**
           * The default constructor will create stack of type with default size 5
           *
           */
          UserDefinedStack() {
              stack = (E[]) new Object[defaultCapacity];
      
          }
      
          /**
           * constructs a stack with initial size
           *
           * @param defaultSize is the size of the stack
           */
          UserDefinedStack(int defaultCapacity) {
              this.defaultCapacity = defaultCapacity;
              stack = (E[]) new Object[defaultCapacity];
          }
      
          public void push(E element) {
              top = top + 1;
              if (defaultCapacity == top) {
                  //System.err.println("Stack is Full!...");
                  // System.out.println("re-creating new resizable Array!..");
                  stack = constructsResizableArray(stack, defaultCapacity);
                  //throw new RuntimeException("Statck Full!...");
              }
              stack[top] = element;
      
          }
      
          /**
           * This method will remove the top of the element and return
           *
           * @return <tt>E</tt> returns top of the element
           *
           */
          public E pop() {
      
              if (top == -1) {
                  System.out.println("Stack is Empty!...");
                  throw new RuntimeException("Statck Empty!...");
              }
              E e = stack[top];
              stack[top] = null;
              top--;
              return e;
          }
      
          /**
           * This method will return top of the element and without remove
           *
           * @param <E> the type of element to insert
           * @return <tt>E</tt> returns top of the element
           *
           */
          public E peek() {
      
              if (top == -1) {
                  System.out.println("Stack is Empty!...");
                  throw new RuntimeException("Statck Empty!...");
              }
              E e = stack[top];
              return e;
          }
      
          public E[] constructsResizableArray(E[] stack, int defaultCapacity) {
              UserDefinedStack.defaultCapacity = defaultCapacity * 2;
              E[] newstack = (E[]) new Object[UserDefinedStack.defaultCapacity];
              int i = 0;
              for (E e : stack) {
                  newstack[i] = e;
                  i++;
              }
              stack = null;
              //System.out.println("New Array returned back");
              return newstack;
          }
      
          /**
           * Iterate the stack over the elements
           *
           */
          public void iterateStack() {
              for (E e : stack) {
                  System.out.print("::" + e);
              }
          }
      
          public long size() {
              return top + 1;
          }
      
          public long capacity() {
              return this.stack.length;
          }
      }
      

      StackIntTest

      import java.util.ArrayList;
      import java.util.Date;
      import java.util.Stack;
      
      /**
       *
       * @author rajasekhar.burepalli
       */
      public class StackIntTest {
      
          public static void main(String[] args) {
              System.out.println("Using Customized Stack!...............");
              Date startDate = new Date();
              System.out.println("StartTime:::" + startDate);
              UserDefinedStack< Integer> is = new UserDefinedStack<>();
              for (int i = 1; i < 1212121; i++) {
                  is.push(i);
              }
              System.out.println("Size::::::" + is.size() + "---Capacity:::" + is.capacity());
              System.out.println("end Time::" + new Date());
      
              System.out.println("Using java.util.Stack!...............");
      
              System.out.println("StartTime:::" + startDate);
              Stack< Integer> is1 = new Stack<>();
              for (int i = 1; i < 1212121; i++) {
                  is1.push(i);
              }
              System.out.println("end Time::" + new Date());
              System.out.println("Size::::::" + is1.size() + "---Capacity:::" + is1.capacity());
      
              System.out.println("Using java.util.ArrayList!...............");
              System.out.println("StartTime:::" + startDate);
              ArrayList< Integer> al = new ArrayList<>();
              for (int i = 1; i < 1212121; i++) {
                  al.add(i);
              }
              System.out.println("end Time::" + new Date());
              System.out.println("Size::::::" + al.size());
      
          }
      }
      

      【讨论】:

        【解决方案4】:
        public static void main(String[] args) {
            Scanner input = new Scanner(System.in);
            //CREATING A STACK USING ARRAYS
            
            //EXAMPLE
            //CREATE AN ARRAY
            int[] numbers = new int[5];
            
            //Create a variable to find out the current elements position
            int pointer = 0 ; 
            
            //Add elements to the array
            for (int i = 0 ; i < numbers.length ; i++){
                numbers[pointer++] = input.nextInt();
            }
            
            //Last In first Out
            //Create a variable to store the removed element
            int temp;
            for (int i = 0; i < numbers.length; i++) {
                pointer -= 1;
                temp = numbers[pointer];
                numbers[pointer] = 0 ;
                
                System.out.println(temp);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-08-11
          • 2015-02-28
          • 1970-01-01
          • 2011-07-22
          • 1970-01-01
          • 2011-02-12
          • 2019-12-01
          相关资源
          最近更新 更多