关闭

数据结构-简单栈的实现

标签: 数据结构
79人阅读 评论(0) 收藏 举报
分类:
简单的栈的实现,栈元素为类型为int,利用一个数组实现,使用时,构造栈有两种方式,一种为不指定栈的大小,
默认原始大小为4,当元素超过当前大小时,则栈大小增长一倍,另一种为指定栈的大小,超过指定大小时抛出异常。
栈的操作有:
push(int value)  压栈
int pop()  弹栈
int peek()  查看栈顶
boolean isEmpty()  判断栈是否为空
boolean isFull()  判断是否已满,若为自动增长模式,即判断是否已达到当前栈的大小的值
public int getSize()  获取栈的大小

/**
 * Created by logaxy on 2017/1/3.
 */
public class MyStack {

    private boolean actoIncrement = true;//栈是否自增长,当指定大小时为否
    private static int INITIALSIZE = 4;//不指定栈大小时的初始化大小
    private int array[];//栈以一个数组实现
    private int top;

    MyStack() {
        array = new int[INITIALSIZE];
        top = -1;
    }

    MyStack(int maxSize) {
        actoIncrement=false;
        if (maxSize < 0 || maxSize == 0)
            throw new IllegalArgumentException();
        array = new int[maxSize];
        top = -1;
    }

    void push(int value) {
        if (isFull()) {
            if (actoIncrement) {
                int[] temp = array;
                array = new int[2 * array.length];
                System.arraycopy(temp, 0, array, 0, temp.length);

            } else {
                throw new IndexOutOfBoundsException();
            }
        }

        array[++top] = value;
    }

    int pop() {
        if (isEmpty())
            throw new IndexOutOfBoundsException();

        return array[top--];
    }

    int peek() {
        if (isEmpty())
            throw new IndexOutOfBoundsException();

        return array[top];
    }

    boolean isEmpty() {
        return (top == -1);
    }

    boolean isFull() {
        return !(top < array.length - 1);
    }

    public int getSize() {
        return array.length;
    }

}


 
测试程序:
public class Main {

    public static void main(String[] args) {
        testStack();
    }

    public static void testStack(){
        MyStack myStack=new MyStack();
        myStack.push(1);
        myStack.push(2);
        myStack.push(3);
        myStack.push(4);
        System.out.println("Top Is: "+myStack.peek());
        System.out.println("Size IS:"+myStack.getSize());
        System.out.println("Is Full: "+myStack.isFull());
        myStack.push(5);
        myStack.push(6);
        System.out.println("Top Is: "+myStack.peek());
        System.out.println("Size IS:"+myStack.getSize());
        System.out.println("Is Full: "+myStack.isFull());
        System.out.println(myStack.pop());
        System.out.println(myStack.pop());
        System.out.println(myStack.pop());
        System.out.println(myStack.pop());
        System.out.println(myStack.pop());
        System.out.println(myStack.pop());
        System.out.println("Is Empty:"+myStack.isEmpty());
        System.out.println("Size IS:"+myStack.getSize());
    }
}

测试结果:
Top Is: 4
Size IS:4
Is Full: true
Top Is: 6
Size IS:8
Is Full: false
6
5
4
3
2
1
Is Empty:true
Size IS:8
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4202次
    • 积分:147
    • 等级:
    • 排名:千里之外
    • 原创:12篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条