Array implementation queue (polling data migration once)
public class Arr_PollMove {
public static void main(String[] args) {
Arr_PollMove queue = new Arr_PollMove(2);
queue.offer("1");
queue.offer("2");
boolean offer3 = queue.offer("3");
System.out.println(offer3);
String poll1 = queue.poll();
System.out.println(poll1);
String poll2 = queue.poll();
System.out.println(poll2);
String poll3 = queue.poll();
System.out.println(poll3);
}
String[] arr;
int tail;
public Arr_PollMove(int capacity){
arr=new String[capacity];
tail=0;
}
public boolean offer(String value){
if (tail==arr.length)return false;
arr[tail++]=value;
return true;
}
public String poll(){
if (tail==0)return null;
String pollS = arr[0];
System.arraycopy(arr,1,arr,0,arr.length-1);
tail--;
return pollS;
}
}
Array to achieve queue (data migration during offer)
public class Arr_OfferMove {
public static void main(String[] args) {
Arr_OfferMove queue = new Arr_OfferMove(2);
queue.offer("1");
queue.offer("2");
String poll1 = queue.poll();
System.out.println(poll1);
boolean offer3 = queue.offer("3");
System.out.println(offer3);
}
String[] arr;
int head,tail;
public Arr_OfferMove(int capacity){
arr=new String[capacity];
tail=0;
head=0;
}
public boolean offer(String value){
if (tail==arr.length&&head!=0) {
System.arraycopy(arr, head, arr, 0, arr.length - head);
tail-=head;
head=0;
}
if (tail==arr.length)return false;
arr[tail++]=value;
return true;
}
public String poll(){
if (tail==head)return null;
String pollS = arr[head++];
return pollS;
}
}
Realize with linked list
public class Linked_queue {
public static void main(String[] args) {
Linked_queue queue = new Linked_queue();
queue.offer("1");
queue.offer("2");
String poll = queue.poll();
System.out.println(poll);
}
class Node{
String value;
Node next;
public Node(String value){
this.value=value;
}
}
Node head,tail;
public void offer(String s){
if(tail==null){
Node current=new Node(s);
head=current;
tail=current;
}else {
tail.next=new Node(s);
tail=tail.next;
}
}
public String poll(){
if (head==null)return null;
String value = head.value;
head=head.next;
if (head==null)tail=null;
return value;
}
}