Design the stack class and implement it in java

1. Introduction

The stack is a data structure that stores data in a last-in, first-out manner.
Design a test class TestStackOfInteger, which uses this class to create a stack, which stores the 10 integers 0, 1, 2, ..., 9, and then displays them in reverse order they.
Design an implementation class StackOfInteger, the elements in the stack are stored in an array named elements. When creating a stack, this array is also created. The parameterless construction method of the class creates an array with a default capacity of 16, and the variable size records the number of elements in the stack. In order to implement the method push(int value), if size<capaciry, assign value to elements[size]. If the search is full (ie size>=capacity), create a new array with twice the current capacity, copy the contents of the current array to the new array, and give the reference value of the new array to the current array.

2. Implementation class

package com.zhuo.base;

public class StackOfInteger {
    
    
    private int[] elements;
    private int size;
    public static final int DEFAULT_CAPACITY = 16;
    public StackOfInteger() {
    
    
        this (DEFAULT_CAPACITY);
    }
    public  StackOfInteger(int capacity) {
    
    
        elements = new int[capacity];
    }
    public void push(int value) {
    
    
        if (size >= elements.length) {
    
    
            int[] temp = new int[elements.length * 2];
            System.arraycopy(elements, 0, temp, 0, elements.length);
            elements = temp;
        }
        elements[size++] = value;
    }
    public int pop() {
    
    
        return elements[--size];
    }
    public int peek() {
    
    
        return elements[size - 1];
    }
    public int getSize() {
    
    
        return size;
    }
    public boolean empty() {
    
    
        return size == 0;
    }
}

Three. Testing

package com.zhuo.base;

public class TestStackOfInteger {
    
    
    public static void main(String[] args) {
    
    
        StackOfInteger stack = new StackOfInteger();
        /*入栈操作*/
        for (int i = 0; i < 10; i++) {
    
    
            stack.push(i);
        }
        System.out.println("当前栈的元素个数: " + stack.getSize());
        System.out.println("当前栈顶元素: " + stack.peek());//返回栈顶元素,而不删除栈顶元素
        /*删除栈顶元素并返回它*/
        System.out.print("取栈的所有元素: ");
        while (!stack.empty()) {
    
    
            System.out.print(stack.pop() + " ");
        }
        System.out.println();
        System.out.println("当前的栈的元素个数: " + stack.getSize());
    }
}

Guess you like

Origin blog.csdn.net/weixin_42768634/article/details/113768545