隊列是一種特殊的線性表,只允許在表的前端進行刪除,在表的后端進行插入,表的前端稱為(front)隊頭,表的后端稱為(rear)隊尾。
所以隊列跟生活的場景很是相似,在電影院買電影票,人們排成一排,第一個人進入隊尾最先到達隊頭后買票進入影院,后面排隊的人按照排隊的次序買到票后進入影院。
所以 隊列是一種先進先出的數據結構(fifo)。
編程實現對循環鏈隊列的入隊和出隊操作。
⑴根據輸入的隊列長度n和各元素值建立一個帶頭結點的循環鏈表表示的隊列(循環鏈隊列),并且只設一個尾指針來指向尾結點,然后輸出隊列中各元素值。
⑵將數據元素e入隊,并輸出入隊后的隊列中各元素值。
⑶將循環鏈隊列的隊首元素出隊,并輸出出隊元素的值和出隊后隊列中各元素值。
當隊列的插入數據時,rear箭頭一直往上走,插入到表的最大下標的位置后停止。在移除數據的時候,front箭頭也會一直往上走。
這可能跟現實中的人們在電影院買電影票的情況有點不符合,一般是買完票,人就往前走,繼續買票,隊伍總是向前移動的。
在計算機中,隊列每刪除一個數據項后,其他數據也可以繼續往移動,但如此一來,處理很大的數據的時候,這樣做的效率很低下,因為每次刪除一個數據就要將剩余的所有數據往前移動。
在刪除數據的時候,隊頭(front)前面的位置就會留空,但由于隊尾(rear)和隊頭(front)這兩個箭頭都一直往上走,所以沒能繼續利用到前面空單元的存儲空間。
為了避免隊列不滿卻不能繼續插入新數據的情況,解決隊列能循環利用的方法就是,當rear箭頭和front箭頭到達最大下標的位置后,重新將它的位置移動到, 表的最初始的位置。
這個就是------循環隊列:
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
|
package datastructure; /** * created by hubbert on 2017/11/11. */ public class queue { private int [] arr ; private int front ; //隊頭指針 private int rear ; //隊尾指針 private int nitems ; //隊列中的個數 private int maxsize; //隊列長度 //使用構造函數進行初始化 public queue( int maxsize ){ this .maxsize = maxsize ; this .arr = new int [ this .maxsize]; this .nitems = 0 ; this .front = 0 ; this .rear = - 1 ; } public boolean isfull(){ return (nitems == maxsize); //判斷隊列是否已滿 } public boolean isempty(){ return (nitems == 0 ); //判斷隊列是否為空 } //插入 public void insert( int number ){ if (!isfull()){ //處理循環隊列 if ( rear == (maxsize - 1 )){ rear = - 1 ; } arr[++rear] = number ; nitems++; } else { system.out.println( "the queue is full!!" ); } } //刪除 public int remove(){ if (!isempty()){ //處理循環隊列 if ( front == maxsize ){ front = 0 ; } nitems--; return arr[front++]; } else { system.err.println ( "the queue is empty!!" ); return - 1 ; } } public static void main(string [] args){ queue queue = new queue( 5 ); queue.insert( 22 ); queue.insert( 33 ); queue.insert( 44 ); queue.insert( 55 ); queue.insert( 66 ); system.out.println( "-----------先刪除隊列中前兩個數據------------" ); system.out.println( "front--->rear:" ); for ( int i = 0 ; i < 2 ; i++ ){ system.out.print(queue.remove() + " " ); } system.out.println( "" ); system.out.println( "-----------繼續使用隊列------------" ); system.out.println( "front--->rear:" ); queue.insert( 1 ); queue.insert( 2 ); while (!queue.isempty()){ system.out.print(queue.remove() + " " ); } } } |
結果如下:
總結
以上就是本文關于java編程隊列數據結構代碼示例的全部內容,希望對大家有所幫助。如有不足之處,歡迎留言指出。期待您的寶貴意見。
原文鏈接:https://www.2cto.com/kf/201711/697416.html