package QueueAndStack;
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 val) {
arr[++top] = val;
}
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;
}
public static void main(String[] args) {
MyStack st = new MyStack(4);
st.push(23);
st.push(12);
st.push(1);
st.push(90);
while (!st.isEmpty()) {
System.out.println(st.pop());
}
}
}
上面是stack的实现,十分简单.直接上代码.
下面是一个简单的队列,同样是简单粗糙的实现:
package QueueAndStack;
public class MyQueue {
long[] arr;
// 有效数据的大小
int elements;
// 队头
int front;
// 队尾
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 val) {
arr[++end] = val;
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 static void main(String[] args) {
MyQueue qu = new MyQueue(3);
qu.insert(1);
qu.insert(2);
qu.insert(3);
qu.insert(4);
qu.insert(5);
qu.insert(6);
while (!qu.isEmpty()) {
System.out.println(qu.remove());
}
}
}
执行上面的结果,很容易发现这个错 . 上面的这个队列,虽然可以简单的实现,先进先出的原则,但是,无法处理队列溢出问题
下面附一个队列溢出问题的解决方案:
package QueueAndStack;
public class MyCycleQueue extends MyQueue {
private int count = 0;
public MyCycleQueue() {
}
public MyCycleQueue(int maxSize) {
super(maxSize);
}
@Override
public void insert(long val) {
if (count < arr.length) {
end++;
arr[end] = val;
elements++;
} else {
end = (count % arr.length);
front = end + 1;
if (front == arr.length) {
front = 0;
}
arr[end] = val;
}
count++;
}
@Override
public long remove() {
elements--;
if (count > arr.length) {
front = count % arr.length;
long val = arr[front];
}
count--;
return arr[front++];
}
public static void main(String[] args) {
MyQueue qu = new MyCycleQueue(3);
qu.insert(1);
qu.insert(2);
qu.insert(3);
qu.insert(4);
qu.insert(5);
qu.insert(6);
qu.insert(7);
qu.insert(8);
while (!qu.isEmpty()) {
System.out.println(qu.remove());
System.out.println(">>>> "+qu.elements);
}
}
}
这是一个循环队列, 如果队列溢出了,则会自动抛弃旧的数据;