1、栈
2、测试栈
3、队列
4、测试队列
1、栈
package com.cwq.ch03;
/**
* 栈,先进后出
* @author Carpoor
* @date 2019年1月28日
*/
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 isEmpty() {
return top == -1;
}
/**
* 判断栈是否已经存满了
*/
public boolean isFull() {
return top == arr.length -1;
}
}
2、测试栈
package com.cwq.ch03;
/**
* 测试栈
* @author Carpoor
* @date 2019年1月28日
*/
public class TestMyStack {
public static void main(String[] args) {
MyStack myStack = new MyStack(4);
myStack.push(26);
myStack.push(15);
myStack.push(72);
myStack.push(21);
System.out.println(myStack.isEmpty());
System.out.println(myStack.isFull());
System.out.println(myStack.peek());
System.out.println(myStack.peek());
while (!myStack.isEmpty()) {
System.out.print(myStack.pop() + ",");
}
}
}
3、队列
package com.cwq.ch03;
/**
* 队列
* 先进先出
* @author Carpoor
* @date 2019年1月28日
*/
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;
if (end == arr.length-1) {//当指针指到数组末端时,重新初始化指针位置。会造成数据覆盖,可以判断队列满了后插入的数据的操作
end = -1;
}
elements++;
}
/**
* 在队头删除数据
*/
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;
}
/**
* 判断队列是否满了
*/
public boolean isFull() {
return elements == arr.length;
}
}
4、测试队列
package com.cwq.ch03;
/**
* 测试队列
* @author Carpoor
* @date 2019年1月28日
*/
public class TestQueue {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue(4);
myQueue.insert(51);
myQueue.insert(26);
myQueue.insert(32);
myQueue.insert(40);
System.out.println(myQueue.isEmpty());
System.out.println(myQueue.isFull());
System.out.println(myQueue.peek());
System.out.println(myQueue.peek());
while (!myQueue.isEmpty()) {
System.out.print(myQueue.remove() + ",");
}
System.out.println();
System.out.println("================分界线=================");
myQueue.insert(51);
myQueue.insert(26);
myQueue.insert(32);
myQueue.insert(40);
System.out.println(myQueue.isEmpty());
System.out.println(myQueue.isFull());
System.out.println(myQueue.peek());
System.out.println(myQueue.peek());
while (!myQueue.isEmpty()) {
System.out.print(myQueue.remove() + ",");
}
}
}