在Java中使用数组创建堆栈类

在Java中使用数组创建堆栈类,java,arrays,stack,Java,Arrays,Stack,我试图用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++) //Movin

我试图用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;
    }
public E-pop()
{
如果(data.length==0)
{
抛出新的EmptyStackException();
}
E poppedObject=数据[0];
for(int i=0;i

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

我建议您看看stack类是如何实现的。它还使用数组,但有一个大小字段,用于保持堆栈的大小

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

来自Stack.pop()

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

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

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];
}

设置一个计数器,告诉您数组中的元素数。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;
}

下面是用户定义的堆栈代码如何在内部实现

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;
    }
}
class UserDefinedStack{
专用静态int defaultCapacity=5;
私有E[]堆栈=null;
int top=-1;
/**
*默认构造函数将创建默认大小为5的类型堆栈
*
*/
UserDefinedStack(){
堆栈=(E[])新对象[defaultCapacity];
}
/**
*构造具有初始大小的堆栈
*
*@param defaultSize是堆栈的大小
*/
UserDefinedStack(int-defaultCapacity){
this.defaultCapacity=默认容量;
堆栈=(E[])新对象[defaultCapacity];
}
公共无效推送(E元素){
顶部=顶部+1;
如果(默认容量==顶部){
//System.err.println(“堆栈已满!”;
//System.out.println(“重新创建新的可调整大小的数组!”;
stack=constructsresizeablearray(stack,defaultCapacity);
//抛出新的运行时异常(“Statck Full!”);
}
堆栈[顶部]=元素;
}
/**
*此方法将删除元素的顶部并返回
*
*@return E返回元素的顶部
*
*/
公共E-pop(){
如果(顶部==-1){
System.out.println(“堆栈为空!”;
抛出新的RuntimeException(“Statck Empty!”);
}
E=堆栈[顶部];
stack[top]=null;
顶部--;
返回e;
}
/**
*此方法将返回元素的顶部,而不删除
*
*@param要插入的元素类型
*@return E返回元素的顶部
*
*/
公共E peek(){
如果(顶部==-1){
System.out.println(“堆栈为空!”;
抛出新的RuntimeException(“Statck Empty!”);
}
E=堆栈[顶部];
返回e;
}
公共E[]ConstructsResizeableArray(E[]堆栈,int defaultCapacity){
UserDefinedStack.defaultCapacity=defaultCapacity*2;
E[]newstack=(E[])新对象[UserDefinedStack.defaultCapacity];
int i=0;
用于(E:堆栈){
新闻标题[i]=e;
i++;
}
stack=null;
//System.out.println(“返回的新数组”);
返回新闻标题;
}
/**
*在元素上迭代堆栈
*
*/
公共空间数据包(){
用于(E:堆栈){
系统输出打印(“:”+e);
}
}
公共长码(){
返回顶部+1;
}
公共长期容量(){
返回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());

    }
}
import java.util.ArrayList;
导入java.util.Date;
导入java.util.Stack;
/**
*
*@author rajasekhar.burepalli
*/
公共类StackIntTest{
公共静态void main(字符串[]args){
System.out.println(“使用定制堆栈!”;
日期开始日期=新日期();
System.out.println(“StartTime::”+startDate);
UserDefinedStackis=newuserdefinedstack();
对于(int i=1;i<1212121;i++){
is.push(i);
}
System.out.println(“大小::“+is.Size()+”---容量:::“+is.Capacity());
System.out.println(“结束时间:”+新日期());
System.out.println(“使用java.util.Stack!”;
System.out.println(“StartTime::”+startDate);
堆栈is1=新堆栈();
对于(int i=1;i<1212121;i++){
is1.推(i);
}
System.out.println(“结束时间:”+新日期());
System.out.println(“大小::”+is1.Size()+“---容量::”+is1.Capacity());
System.out.println(“使用java.util.ArrayList!……”;
System.out.println(“StartTime::”+startDate);
ArrayListal=新的ArrayList();
对于(int i=1;i<1212121;i++){
al.添加(i);
}
System.out.println(“结束时间:”+新日期());
System.out.println(“大小::”+al.Size());
}
}
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
//使用数组创建堆栈
//范例
//创建一个数组
int[]数字=新的int[5];
//创建一个变量以找出当前元素的位置
int指针=0;
//向数组中添加元素
for(int i=0;iclass 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;
    }
}
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());

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