[数据结构]P1.3 栈 Stack

* 注: 本文/本系列谢绝转载,如有转载,本人有权利追究相应责任。 

栈是一种先进后出的结构(FILO),常见的操作有:push 入栈、pop删除栈顶元素并返回、peek 查看栈顶元素

与其他线性结构一样,栈的实现也有数组和链表两种形式。如何实现依据具体应用,例如栈的大小是确定的,那么使用数组实现开销最小,

如果栈需要可扩展,则建议使用链表实现。

 

这边使用数组实现一个,使用链表实现的可以自行研究。

Java代码:

 

package ds3.stack;

import java.util.Arrays;

public class ArrayStack {
    static class Stack{
        long[] data;
        int top = -1;
        int maxSize;
        int size;
        Stack(int maxSize){
            this.maxSize = maxSize;
            data = new long[this.maxSize];
        }

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

        public boolean isFull(){
            return top + 1 == data.length;
        }

        /**
         * 将元素推进数组
         * @param value
         */
        public void push(long value){
            if(isFull()){
                System.out.println("The stack is full!");
            }else{
                this.data[++top] = value;
                size++;
            }
        }

        /**
         * 查看栈顶元素
         */
        public long peek(){
            return this.data[this.top];
        }

        /**
         * 查看栈顶元素并删除栈顶元素
         * @return
         */
        public Long pop(){
            Long result = null;
            if(isEmpty()){
                System.out.println("The stack is empty!");
            }else{
                result = this.data[--top];
                size--;
            }
            return result;
        }

        public void foreachPrint(){
            System.out.println(Arrays.toString(Arrays.copyOf(data,size)));
        }

    }

    public static void main(String[] args) {
        Stack stack = new Stack(4);
        stack.foreachPrint();
        stack.push(1);
        stack.foreachPrint();
        stack.push(2);
        stack.foreachPrint();
        stack.push(3);
        stack.foreachPrint();
        stack.push(4);
        stack.foreachPrint();
        stack.push(5);
        stack.foreachPrint();
        System.out.println(stack.peek());
        stack.foreachPrint();
        System.out.println(stack.pop());
        stack.foreachPrint();
    }
}

result:

[]
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
The stack is full!
[1, 2, 3, 4]
4
[1, 2, 3, 4]
3
[1, 2, 3]

 

posted @ 2019-04-18 19:09  yosql473  阅读(202)  评论(0编辑  收藏  举报