1.数组实现队列
public class Queue<T> {
private T[] arr;
public Queue(int size) {
arr = (T[]) new Object[size];
}
private int length = 0;
public int getLength() {
return length;
}
public void push(T data) {
if (length + 1 <= arr.length) {
arr[length++]=data;
} else {
throw new RuntimeException("队列满!");
}
}
public T pop(){
if (length==0){
throw new RuntimeException("队列为空,无法抛出元素!");
}
T data =arr[0];
T [] temp = (T[]) new Object[arr.length];
IntStream.rangeClosed(1, arr.length - 1).forEach(i -> temp[i - 1] = arr[i]);
arr=temp;
length--;
return data;
}
}
2.链表实现队列
public class Queue2 {
LinkList linkList;
public Queue2(){
linkList=new LinkList();
}
public void push(int data){
linkList.push(data);
}
public int pop(){
return linkList.pop();
}
public int size(){
return linkList.getLength();
}
class Node {
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
class LinkList {
Node head = new Node(0);
int length = 0;
public void push(int data) {
if (head.next == null) {
head.next = new Node(data);
} else {
Node node = new Node(data);
node.next = head.next;
head.next = node;
}
length++;
}
public int pop() {
if (head.next == null) {
throw new RuntimeException("栈中无元素,无法弹出!");
}
Node p = head.next;
Node q = head;
while (p.next != null) {
p = p.next;
q = q.next;
}
q.next = null;
length--;
return p.data;
}
public int getLength() {
return length;
}
}
}