转载请注明出处:http://blog.csdn.net/u011569040/article/details/46004687
栈的构造和应用:
public class MyStack {
private long[] arr;
private int top;
//默认的构造方法
public MyStack(){
arr = new long[10];
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 isEmply(){
return top == -1;
}
//判断是否满了
public boolean isFull(){
return top ==arr.length -1;
}
public void print(){
for(long num : arr){
System.out.print(num + ",");
}
}
}
public class Test {
public static void main(String[] args) {
MyStack ms = new MyStack(4);
ms.push(23);
ms.push(12);
ms.push(1);
ms.push(9);
ms.print();
System.out.println(ms.isEmply());
System.out.println(ms.isFull());
System.out.println(ms.peek());
while(!ms.isEmply()){
System.out.print(ms.pop() + ",");
}
System.out.println(ms.isEmply());
System.out.println(ms.isFull());
ms.print();
}
}
结果:
列队:
public class MyQueue {
//底层使用数组
private long[] arr;
//有效数据的大小
private int elements;
//对头
private int front;
//队尾
private int end;
//默认构造方法
public MyQueue(){
arr = new long[10];
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 boolean isFull(){
return elements == arr.length ;
}
}
public class TestMyQueue {
public static void main(String[] args) {
MyQueue mq = new MyQueue(4);
mq.insert(23);
mq.insert(45);
mq.insert(13);
mq.insert(1);
System.out.println(mq.isFull());
System.out.println(mq.isEmpty());
System.out.println(mq.peek());
System.out.println(mq.peek());
while(!mq.isEmpty()){
System.out.println(mq.remove() + " ");
}
}
}
但是现在如果再insert()数据就会报错
所以要用循环队列:
只需要修改insert()和remove():
//添加数据,从队尾加入
public void insert(long value){
if(end == arr.length - 1){
end = -1;
}
arr[++end] = value;
elements++;
}
//删除数据,从对头删除
public long remove(){
long value = arr[front++];
if(front == arr.length){
front = 0;
}
elements--;
return value ;
}
public class TestMyQueue {
public static void main(String[] args) {
MyCycleQueue mq = new MyCycleQueue(4);
mq.insert(23);
mq.insert(45);
mq.insert(13);
mq.insert(1);
System.out.println(mq.isFull());
System.out.println(mq.isEmpty());
// System.out.println(mq.peek());
// System.out.println(mq.peek());
while(!mq.isEmpty()){
System.out.println(mq.remove() + " ");
}
mq.insert(23);
mq.insert(45);
mq.insert(13);
mq.insert(1);
while(!mq.isEmpty()){
System.out.println("xie "+mq.remove() + " ");
}
}
}
结果: