1. 泛型循环队列
package datastructure.queue;
import java.lang.reflect.Array;
public class GenericSqCircQueue<T> {
public static final int MAX_QUEUE_SIZE = 20;
T[] data;
int head;
int tail;
@SuppressWarnings("unchecked")
GenericSqCircQueue(Class<T> type) {
data = (T[]) Array.newInstance(type, MAX_QUEUE_SIZE);
head = tail = 0;
}
public boolean enSqCircleQueue(T elem) {
if ((tail + 1) % 100 == head) {
System.out.println("CircleQueue is full");
return false;
}
data[tail % MAX_QUEUE_SIZE] = elem;
tail++;
return true;
}
public T deSqCircleQueue() {
if (head == tail) {
System.out.println("Circle Queue is Empty");
return null;
}
T tempValue = data[head % MAX_QUEUE_SIZE];
head++;
return tempValue;
}
public int lengthOfCircleQueue() {
return (tail - head + MAX_QUEUE_SIZE) % MAX_QUEUE_SIZE;
}
public String toString() {
String resultString = "";
if (head == tail) {
return "Empty";
}
for (int i = head; i < tail; i++) {
resultString += data[i % MAX_QUEUE_SIZE] + " ";
}
return resultString;
}
public static void main(String[] args) {
GenericSqCircQueue<Integer> queue = new GenericSqCircQueue<Integer>(Integer.class);
System.out.println("打印循环队列:" + queue.toString());
System.out.println("循环队列元素个数:" + queue.lengthOfCircleQueue());
queue.enSqCircleQueue(1);
queue.enSqCircleQueue(2);
queue.enSqCircleQueue(6);
queue.enSqCircleQueue(8);
queue.enSqCircleQueue(5);
System.out.println("打印循环队列:" + queue.toString());
System.out.println("循环队列元素个数:" + queue.lengthOfCircleQueue());
queue.deSqCircleQueue();
System.out.println("打印循环队列:" + queue.toString());
System.out.println("循环队列元素个数:" + queue.lengthOfCircleQueue());
}
}
打印循环队列:Empty
循环队列元素个数:0
打印循环队列:1 2 6 8 5
循环队列元素个数:5
打印循环队列:2 6 8 5
循环队列元素个数:4
2. 泛型栈
package datastructure.stack;
import java.lang.reflect.Array;
public class GenericSqStack<T> {
public static final int STACK_SIZE = 15;
public int stackSize;
public T[] data;
@SuppressWarnings("unchecked")
GenericSqStack(Class<T> type) {
this.stackSize = 0;
this.data = (T[]) Array.newInstance(type, STACK_SIZE);
}
public String toString() {
String result = "";
for (int i = 0; i < this.stackSize; i++) {
result += data[i] + " ";
}
return result;
}
public boolean push(T elem) {
if (this.stackSize == STACK_SIZE) {
System.out.println("Stack full.");
return false;
}
this.data[this.stackSize] = elem;
this.stackSize++;
return true;
}
public T pop() {
if (this.stackSize == 0) {
System.out.println("StackEmpty.");
return null;
}
T elem = data[this.stackSize - 1];
this.stackSize--;
return elem;
}
public boolean isEmpty() {
if (this.stackSize == 0) {
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
GenericSqStack<Integer> stack = new GenericSqStack<Integer>(Integer.class);
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
System.out.println("入栈,并打印栈:" + stack.toString());
int temp = stack.pop();
System.out.println("出栈,并打印栈顶元素:" + temp);
System.out.println("栈是否为空:" + stack.isEmpty());
}
}
入栈,并打印栈:1 2 3 4
出栈,并打印栈顶元素:4
栈是否为空:false