Java数据结构与算法《三》栈与队列

来源:互联网 发布:软件工作室图片 编辑:程序博客网 时间:2024/06/16 08:29

实现栈结构

public class MyStack{    //底层实现是一个数组    private long[] arr;    private int top;    //默认的构造方法    public MyStack(){        arr = new long[100];        top =-1;    }    //带参数构造方法 参数为数组的初始化大小‘    public MyStack(int maxSize){        arr = new long[maxSize];        top=-1;    }    //添加数据    public void push(int value){        arr[++top]=value;    }    //删除数据    public long pop(){        return arr[top--];    }    //查看数据    public long peek(){        return arr[top];    }    //判断是否为空    public boolean isEmpty(){        return top == -1;    }}

实现队列

public class MyQueue{    //底层使用数组    private long arr[];    //有效数据的大小    private int elements;    //对头    private int front;    //队尾    private int end;    //默认构造方法    public MyQueue(){        arr = new arr[100];        elements =0;        front =0;        end =-1;    }    //带参数的构造方法 参数为数组的大小    public MyQueue(int maxSize){        arr = new long[maxSize];        elements =0;        front =0;        end =-1;    }    //添加数据 从尾部插入    public void insert(long value){        arr[++end] =value;        elements++;    }    //删除数据 从对头删除    public long remove(){        elements--;        return arr[front++];    }    //查看数据 从头部查看    public long peek(){        return arr[front];    }    //判断是否为空    public boolean isEmpty(){        return elements==0;    }}

实现双端队列

public class MyCycleQueue{    //底层使用数组实现    private long[] arr;    //有效数据的大小    private int elements;    //队头    private int front;    //队尾    private int end;    //默认构造器    public MyCycleQueue(){        arr = new long[10];        elements =0;        front =0;        end =-1;    }    //带参数的构造方法    public MyCycleQueue(int maxSize){        arr = new long[maxSize];        elements =0;        front=0;        end =-1;            }    //删除数据 从头部删除    public long remove(){        long value = arr[front++];        if(front== arr.length){            front =0;        }        elements--;        return value;    }    //查看数据 从头部查看    public long peek(){        return arr[front];    }    //判断是否为空    public boolean isEmpty(){        return elements ==0;    }}
0 0
原创粉丝点击