一、设计循环队列(力扣622题: 设计循环队列)
public class MyCircularQueue {
private int[] elem;
private int front;
private int rear;
public MyCircularQueue(int k) {
this.elem = new int[k + 1];
}
public boolean enQueue(int value) {
if(isFull()) {
return false;
}
this.elem[this.rear] = value;
this.rear = (this.rear + 1) % this.elem.length;
return true;
}
public boolean deQueue() {
if(isEmpty()) {
return false;
}
this.front = (this.front + 1) % this.elem.length;
return true;
}
public int Front() {
if(isEmpty()) {
return -1;
}
return this.elem[this.front];
}
public int Rear() {
if(isEmpty()) {
return -1;
}
int index = -1;
if(this.rear == 0) {
index = elem.length - 1;
}else {
index = this.rear - 1;
}
return this.elem[index];
}
public boolean isEmpty() {
return this.front == this.rear;
}
public boolean isFull() {
return this.front == (this.rear + 1) % this.elem.length;
}
}
public class TestDemo {
public static void main(String[] args) {
MyCircularQueue myCircularQueue = new MyCircularQueue(5);
myCircularQueue.enQueue(4);
myCircularQueue.enQueue(5);
myCircularQueue.enQueue(4);
myCircularQueue.deQueue();
System.out.println(myCircularQueue.Front());
System.out.println(myCircularQueue.Rear());
}
}
二、设计栈
public class MyStack {
public int[] elem;
public int usedSize;
public MyStack() {
this.elem = new int[5];
}
public void push(int val) {
if(isFull()) {
System.out.println("栈满了!");
return;
}
this.elem[this.usedSize++] = val;
}
public boolean isFull() {
return this.usedSize == this.elem.length;
}
public int pop() throws RuntimeException {
if(empty()) {
throw new RuntimeException("栈为空!");
}
int val = this.elem[this.usedSize - 1];
this.usedSize--;
return val;
}
public boolean empty() {
return this.usedSize == 0;
}
public int peek() {
if(empty()) {
throw new RuntimeException("栈为空!");
}
return this.elem[this.usedSize - 1];
}
}
public class TestDemo {
public static void main1(String[] args) {
MyStack myStack = new MyStack();
myStack.push(1);
myStack.push(2);
myStack.push(3);
myStack.push(4);
System.out.println(myStack.pop());
System.out.println(myStack.peek());
System.out.println(myStack.empty());
}
}