java的队列实现方法_Java实现队列的三种方法集合
數(shù)組實(shí)現(xiàn)隊(duì)列
//數(shù)組實(shí)現(xiàn)隊(duì)列
class queue{
int[] a = new int[5];
int i = 0;
//入隊(duì)操作
public void in(int m) {
a[i++] = m;
}
// 出隊(duì)列操作 取出最前面的值 通過(guò)循環(huán)遍歷把所有的數(shù)據(jù)向前一位
public int out() {
int index = 0;
int temp = a[0];
for(int j = 0;j < i;j++) {
a[j] = a[j + 1];
}
return temp;
}
}
ArrayList實(shí)現(xiàn)隊(duì)列
//集合實(shí)現(xiàn)隊(duì)列
class queue{
List list = new ArrayList();
int index = 0;
public void in(int n) {
list.add(n);
index++;
}
//出隊(duì)列操作
//出隊(duì)
public int out(){
if(!list.isEmpty()){
index--;
return list.remove(0);
}
return -1;
}
}
兩個(gè)堆棧實(shí)現(xiàn)隊(duì)列
//兩個(gè)堆棧實(shí)現(xiàn)一個(gè)隊(duì)列
class queue3 {
Stack stackA = new Stack();
Stack stackB = new Stack();
//入隊(duì)
public void in(int n) {
stackA.push(n);
}
//出隊(duì) 我們把A里面的元素遍歷拿出放入B中 再拿出B中的第一個(gè)元素
public int out() {
//判斷b棧有沒有元素 有返回false 無(wú)返回真
if(stackB.isEmpty()) {
while(!stackA.isEmpty()) {
stackB.push(stackA.pop());
}
}
return stackB.pop();
}
}
補(bǔ)充知識(shí):java使用鏈表實(shí)現(xiàn)隊(duì)列
隊(duì)列使用Java進(jìn)行鏈表實(shí)現(xiàn),在網(wǎng)上找到了一張圖,很好,借鑒一下
設(shè)置兩個(gè)結(jié)點(diǎn)node,front指向隊(duì)首元素,rear指向隊(duì)尾;
上代碼:
public class LinkedQueue {
Node front;//隊(duì)頭指針,指向隊(duì)頭節(jié)點(diǎn)
Node rail;//隊(duì)尾指針,指向隊(duì)尾節(jié)點(diǎn)
int size = 0;//記錄隊(duì)列長(zhǎng)度
//構(gòu)造函數(shù)
public LinkedQueue() {
front = rail = null;
}
public boolean isEmpty() {
return size == 0 ? true : false;
}
//添加元素
public boolean addQueue(Object ele) {
if (size == 0) {
front = new Node(null, ele);
rail = front;
size++;
return true;
}
Node s = new Node(null, ele);
//這塊有個(gè)主意的地方,一旦rail設(shè)置了next屬性,因?yàn)閒ront節(jié)點(diǎn)與rail節(jié)點(diǎn)指向了同一個(gè)node節(jié)點(diǎn),持有同一個(gè)結(jié)點(diǎn)的一個(gè)引用,因此front節(jié)點(diǎn)next屬性也被填充
rail.setNext(s);
rail = s;
size++;
return true;
}
/**
* 刪除元素,出隊(duì)列
* @return
*/
public boolean deleteQueue() {
if (isEmpty()) {
System.out.println("當(dāng)前隊(duì)列為空");
return false;
}
front = front.next;
size--;
return true;
}
public static void main(String[] args) {
LinkedQueue queue = new LinkedQueue();
queue.addQueue(1);
queue.addQueue(2);
queue.addQueue(3);
queue.deleteQueue();
}
}
/**
* 首先鏈表底層是一個(gè)個(gè)結(jié)點(diǎn)
*/
class Node {
Node next;
Object element;
public Node(Node next, Object element) {
this.next = next;
this.element = element;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public Object getElement() {
return element;
}
public void setElement(Object element) {
this.element = element;
}
}
總結(jié)
以上是生活随笔為你收集整理的java的队列实现方法_Java实现队列的三种方法集合的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: android 输入光标修改颜色_2.2
- 下一篇: java顺序表冒泡排序_冒泡排序就这么简