صف یا Queue یک حافظه ی First In – First Out است. یعنی داده ای که زودتر در این حافظه قرار میگیرد، زودتر از همه هم از حافظه خارج میشود.
معمولا برای صف متدهای زیر تعریف میشود:
متد insert: یک داده به انتهای صف اضافه میکند.
متد delete: داده ی ابتدای صف را برمیگرداند و سپس از صف خارج میکند.
متد peek: داده ی ابتدای صف را برمیگرداند ولی آن را از صف خارج نمیکند.
متد isEmpty: در صورتی که صف خالی باشد مقدار true را برمیگرداند.
متد isFull: در صورتی که ظرفیت حافظه ی صف پر شده باشد مقدار true را برمیگرداند.
متد size: تعداد اعضای منتظر در صف را برمیگرداند.
متد maxSize: ظرفیت صف را برمیگرداند.
Queue.java
/*Queue
22 Nov 2015
06 Dec 2015
Java Language
By: Sina Moradi
http://Samiantec.ir*/
public class Queue {
private int data[];
private int front=0;
private int rear=0;
public Queue() {
data = new int[100];
}
public Queue(int n) {
data = new int[n];
}
public void insert(int x) {
if (isFull()) {
System.out.println("Error");
System.exit(0);
}
data[rear] = x;
rear = (rear + 1) % data.length;
}
public int delete() {
if (isEmpty()) {
System.out.println("Error");
System.exit(0);
}
int temp=data[front];
front = (front + 1) % data.length;
return temp;
}
public int peek() {
if (isEmpty()) {
System.out.println("Error");
System.exit(0);
}
int temp=data[front];
return temp;
}
public int size() {
if (rear >= front)
return rear - front;
return data.length - (front - rear);
}
public boolean isEmpty() {
return rear == front;
}
public boolean isFull() {
return size() == data.length - 1;
}
}
Test.java
/*Queue
22 Nov 2015
06 Dec 2015
Java Language
By: Sina Moradi
http://Samiantec.ir*/
import java.util.*;
public class Test {
public static void main(String[] args) {
Queue a=new Queue(5);
a.insert(1);
a.insert(2);
a.insert(3);
a.insert(4);
a.delete();
a.insert(5);
//Now we print all queue items
while (!a.isEmpty()) {
System.out.println(a.delete());
}
}
}