The queue is a FIFO linear table;
Because the queue is a linear table, there are two implementations of sequential storage and chained storage.
first, sequential storage implementation
Because the characteristics of the queue are: added from the end of the team, removed from the head, so if the tail of the array is used as the tail, the array header as a team head, when the element is deleted, the time complexity is O (n);
So we need to implement the loop array, and maintain two properties front, Rear,front to record the position of the team head, rear record the next position in the tail of the team, for example:
This makes it possible to make full use of the space in the array, but the predetermined space can no longer be changed;
The code is implemented as follows:
Package org.xiazdong.list;
public class Myarrayqueue<t> {
private int front;
private int rear;
private int length;
Private t[] T;
Public Myarrayqueue () {
front = rear = length = 0;
T = (t[]) new object[20];
}
public void Append (T e) throws exception{
if (length==t.length) {
throw new queueoverflowexception ();
}
length++;
T[rear] = e;
Rear = (rear+1)%t.length;
}
Public T Remove () throws exception{
if (length<=0) {
throw new queueoffflowexception ();
}
T e = T[front];
length--;
Front = (front + 1)%t.length;
return e;
}
public int GetSize () {
return length;
}
}
Class Queueoverflowexception extends exception{public
queueoverflowexception () {
super ();
}
@Override public
String getMessage () {
return ' queue overflow ';
}
}
Class Queueoffflowexception extends exception{public
queueoffflowexception () {
super ();
}
@Override public
String getMessage () {
return "queue empty";
}
}
second, chain-type storage implementation
Chain-type storage is simply a single-linked list +front, rear pointers;
Front points to the head node, and rear points to the last one;
Review the definition of the head node: nodes that do not have any meaning and are used in order to operate a single linked list;
The code is implemented as follows:
Package org.xiazdong.list;
public class Mylistqueue<t> {
private beginnode front;
Private Node rear;
Public Mylistqueue () {
front = new Beginnode (0,null);
Rear = front;
}
public void Append (T e) {
node n = new Node (e,null);
Rear.next = n;
Rear = n;
front.elem++;
}
Public T Remove () throws exception{
if (front.elem<=0) {
throw new Exception ();
}
T e = Front.next.elem;
Front.next = Front.next.next;
front.elem--;
if (front.elem==0) {
rear = front;
}
return e;
}
Class Node {
private T elem;
Node Next;
Public Node () {
elem = null;
next = null;
}
Public Node (T elem, node next) {
This.elem = Elem;
This.next = next;
}
}
Class Beginnode extends Node {
int elem;
Public Beginnode (int elem, Node next) {
This.elem = Elem;
This.next = Next;}}}