队列
package ch03;
/**
* @author lixin
* @date 2018年7月18日
* @Description 队列类(在)
*/
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) {
if (end == arr.length - 1) {
end = -1;
}
arr[++end] = value;
elements++;
}
/**
* 从队头删除(先进先出)
*/
public long remove() {
System.out.println("当前移除"+front);
//循环队列从对头删除
if(front == arr.length-1) {
front = 0;
}
elements--;
return arr[front++];
}
/**
* 查看对头数据
*/
public long peek() {
return arr[front];
}
public static void main(String[] args) {
MyQueue myQueue = new MyQueue(4);
myQueue.insert(11);
myQueue.insert(12);
myQueue.insert(13);
myQueue.insert(14);
while (myQueue.elements > 0) {
System.out.println(myQueue.remove());
}
myQueue.insert(11);
myQueue.insert(44);
while (myQueue.elements > 0) {
System.out.println(myQueue.remove());
}
}
}
栈
package ch03;
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(long value) {
arr[++top] = value;
}
/**
* 移除数据
*/
public long pop() {
return arr[top--];
}
/**
* 查看栈顶数据
*/
public long peek() {
return arr[top];
}
/**
* 判断栈是否为空
*/
public boolean isNull() {
return top == -1;
}
/**
* 判断是否满了
*/
public boolean isFull() {
return top == arr.length - 1;
}
public static void main(String[] args) {
MyStack myStack = new MyStack(4);
myStack.push(11);
myStack.push(12);
myStack.push(13);
myStack.push(14);
System.out.println(myStack.peek());
while(myStack.top>-1){
System.out.println(myStack.pop()+" ");;
}
System.out.println(myStack.isFull());
System.out.println(myStack.isNull());
}
}