數組實現隊列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
//數組實現隊列 class queue{ int [] a = new int [ 5 ]; int i = 0 ; //入隊操作 public void in( int m) { a[i++] = m; } // 出隊列操作 取出最前面的值 通過循環遍歷把所有的數據向前一位 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實現隊列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
//集合實現隊列 class queue{ List<Integer> list = new ArrayList<Integer>(); int index = 0 ; public void in( int n) { list.add(n); index++; } //出隊列操作 //出隊 public int out(){ if (!list.isEmpty()){ index--; return list.remove( 0 ); } return - 1 ; } } |
兩個堆棧實現隊列
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
//兩個堆棧實現一個隊列 class queue3 { Stack<Integer> stackA = new Stack<Integer>(); Stack<Integer> stackB = new Stack<Integer>(); //入隊 public void in( int n) { stackA.push(n); } //出隊 我們把A里面的元素遍歷拿出放入B中 再拿出B中的第一個元素 public int out() { //判斷b棧有沒有元素 有返回false 無返回真 if (stackB.isEmpty()) { while (!stackA.isEmpty()) { stackB.push(stackA.pop()); } } return stackB.pop(); } } |
補充知識:java使用鏈表實現隊列
隊列使用Java進行鏈表實現,在網上找到了一張圖,很好,借鑒一下
設置兩個結點node,front指向隊首元素,rear指向隊尾;
上代碼:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
|
public class LinkedQueue { Node front; //隊頭指針,指向隊頭節點 Node rail; //隊尾指針,指向隊尾節點 int size = 0 ; //記錄隊列長度 //構造函數 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); //這塊有個主意的地方,一旦rail設置了next屬性,因為front節點與rail節點指向了同一個node節點,持有同一個結點的一個引用,因此front節點next屬性也被填充 rail.setNext(s); rail = s; size++; return true ; } /** * 刪除元素,出隊列 * @return */ public boolean deleteQueue() { if (isEmpty()) { System.out.println( "當前隊列為空" ); 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(); } } /** * 首先鏈表底層是一個個結點 */ 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; } } |
以上這篇Java實現隊列的三種方法集合就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/NuanShuTT/article/details/108573687