資料結構java版之《棧和佇列》
阿新 • • 發佈:2019-01-08
1、棧。
(Android的Activity載入是基礎棧結構的)
底層使用陣列實現
package ch4; /** * 棧 * @author Howard * 特點: * 1、通常情況作為程式設計師的工具集來用 * 2、受限訪問,不可直接拿中間資料 * 3、更加抽象(主要通過介面定義) * 4、表現形式為先進後出 */ public class MyStack { //底層使用陣列來儲存資料 private long arr[]; //棧頂的指標 private int top; /** * 預設的構造,建立長度為100的陣列 */ public MyStack(){ arr = new long[100]; top = -1; } /** * 帶參構造 * 建立物件的時候指定陣列大小 * @param maxSize */ public MyStack(int maxSize){ arr = new long[maxSize]; //指定為-1原因是,新增陣列,保證指標指向第一條資料 top = -1; } /** * 壓棧,新增資料 * @param value */ public void push(long value){ //++top保證第一次新增加入到陣列第一個位置 arr[++top] = value; } /** * 出棧,減少資料 * @return */ public long pop(){ //top--保證第一次出棧為棧頂最頂端資料 return arr[top--]; } /** * 檢視資料,每一次拿出棧頂的資料 * 底層是陣列的最後一條資料 * @return */ public long peek(){ return arr[top]; } /** * 判斷棧是否為空 * @return */ public boolean isEmpty(){ //指標指向-1位置,說明陣列為空,也就是棧為空 return top == -1; } /** * 判斷陣列是否滿了 * @return */ public boolean isFull(){ //top位於陣列的最大值索引時,滿棧 return top == arr.length-1; } }
測試棧:
package ch4; public class TestMyTask { public static void main(String[] args) { MyStack myStack = new MyStack(5); myStack.push(23); myStack.push(13); myStack.push(33); myStack.push(20); myStack.push(27); System.out.println(myStack.isEmpty()); System.out.println(myStack.isFull()); System.out.println(myStack.peek()); System.out.println(myStack.peek()); while(!myStack.isEmpty()){ System.out.println(myStack.pop()); } System.out.println(myStack.isEmpty()); System.out.println(myStack.isFull()); } }
列印輸出:
false
true
27
27
27
20
33
13
23
true
false
2、佇列
(Android中的Message是基於佇列結構的)
底層使用陣列實現
package ch4; /** * 1、先進先出與棧相反 * 2、通常情況作為程式設計師的工具集來用 * @author Howard */ public class MyQueue { //底層使用陣列 private long[] arr; //定義頭指標 private int top; //定義尾指標 private int rear; //記錄元素個數 private int elements; public MyQueue(int maxSize){ arr = new long[maxSize]; top = 0; rear = -1; } /** * 增加資料 * @param value */ public void insert(long value){ if(rear == arr.length -1){ //實現迴圈使用。超過以往值就覆蓋原來內容 rear = -1; } arr[++rear] = value; elements++; } /** * 移除資料,移除的佇列最前面的資料 * @return */ public long remove(){ if(top == arr.length){ //實現迴圈使用。底層top指向了最頂層,讓指標再回到陣列最開頭 top = 0; } elements --; return arr[top++]; } /** * 檢視資料,檢視的佇列頭部的資料 * @return */ public long peek(){ return arr[top]; } /** * 判斷是否為空 * @return */ public boolean isEmpty(){ return elements == 0; } /** * 是否滿了 * @return */ public boolean isFull(){ return elements == arr.length; } }
測試佇列:
false
true
12
12
12
---------------------
12
32
18
10
2
true
false
現在使用陣列實現棧和佇列,等學習連結串列時,再用連結串列實現之。