生活随笔
收集整理的這篇文章主要介紹了
数组模拟队列(代码实现)
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
數(shù)據(jù)結(jié)構(gòu)可分為兩種,第一種是線性結(jié)構(gòu),第二種是非線性結(jié)構(gòu),線性結(jié)構(gòu)又分為連續(xù)存儲(chǔ)和鏈表存儲(chǔ)。
常見(jiàn)的線性結(jié)構(gòu)有數(shù)組,鏈表,隊(duì)列,棧;
以下是數(shù)組模擬隊(duì)列的實(shí)現(xiàn)(隊(duì)列特點(diǎn)就是先進(jìn)先出):
public class ArrayQueueDemo {public static void main(String
[] args
) {ArrayQueue queue
= new ArrayQueue(3);char key
= ' '; Scanner scanner
= new Scanner(System
.in
);boolean f
= true;while(f
){System
.out
.println("s:顯示隊(duì)列");System
.out
.println("a:添加數(shù)據(jù)");System
.out
.println("e:退出程序");System
.out
.println("h:顯示頭部數(shù)據(jù)");System
.out
.println("g:取出數(shù)據(jù)");key
= scanner
.next().charAt(0);switch(key
) {case 's':queue
.show();break;case 'a':System
.out
.println("輕輸入一個(gè)數(shù)據(jù)");int value
= scanner
.nextInt();queue
.add(value
);break;case 'h':try {int res
= queue
.head();System
.out
.println(res
);} catch (Exception e
) {System
.out
.println(e
.getMessage());}break;case 'g':try {int res
= queue
.get();;System
.out
.println(res
);} catch (Exception e
) {System
.out
.println(e
.getMessage());}break;case 'e':scanner
.close();f
= false;break;default:break;}}System
.out
.println("退出程序");}}class ArrayQueue{private int maxSize
; private int front
; private int rear
; private int[] arr
;public ArrayQueue(int arrMaxSize
) {maxSize
= arrMaxSize
;arr
= new int[maxSize
];front
= -1; rear
= -1;}public boolean isFull() {return rear
== maxSize
- 1;}public boolean isNull() {return front
== rear
;}public void add(int num
) {if(isFull()) {System
.out
.println("隊(duì)列已經(jīng)滿了,不能添加數(shù)據(jù)");return;}rear
++;arr
[rear
] = num
;}public int get() {if(isNull()) {throw new RuntimeException("隊(duì)列為空,沒(méi)有數(shù)據(jù)");}front
++;return arr
[front
];}public void show() {if(isNull()) {System
.out
.println("隊(duì)列為空,沒(méi)有數(shù)據(jù)");return;}for(int i
= 0; i
<arr
.length
;i
++) {System
.out
.println(arr
[i
]);}}public int head() {if(isNull()) {throw new RuntimeException("隊(duì)列為空");}return arr
[front
+1];}}
總結(jié)
以上是生活随笔為你收集整理的数组模拟队列(代码实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。