《Java資料結構和演算法》第二版 Robert lafore 編程作業 第四章
/* 編程作業 4.1 為queue.java 程式(清單4.4)的Queue類中寫一個方法,顯示隊列的 內容。注意這並不是要簡單的顯示出數組的內容。它要求按資料項目插入的隊 列的順序,從第一個插入的資料項目到最後一個插入的資料項目顯示出來。不要 輸出因為在數組末端迴繞而折成兩半的樣子。注意無論front和rear在什麼 位置上,都要正確顯示出一個資料項目和沒有資料項目的情況。 4.2 根據本章裡對雙端隊列的討論編寫一個Deque類,它應該包括 insertLeft()、insertRight()、removeLeft()、removeRight()、 isEmpty()、isFull()方法。要求像隊列那樣支援在資料末端的迴繞。 4.3 編寫一個基於上機作業4.2的Deque類的棧類。這個棧類應該與 stack.java程式(清單4.1)中的StackX類具有機同的方法和功能。 4.4 清單4.6中展示的優先順序隊列能夠快速地刪除最高優先順序的資料項目,但是 插入資料項目較慢。還要包括一個顯示優先順序隊列內容的方法,要求和上機作 業4.1中一樣。 4.5 隊列通用於類比人、汽車、飛機、業務等等的流動情況。應用queue.java 程式(清單4.4)的Queue類,編寫一個程式類比超市的收款隊列。可以用上機 作業4.1的display()方法,顯示出顧客的幾條隊列。可以通過敲擊一個鍵插入 一個新的顧客。為顧客選擇在哪一個隊列上。收銀員為每個顧客服務的時間是 隨機的(可假定為按照顧客買了多少東西而定)。一旦結完賬,就從隊列中刪 除該顧客。為了簡單起見,通過敲擊鍵類比時間的流逝。可能每點擊一下鍵表 示時間過去了1分鐘。(當然,java有更複雜的方式來處理時間。) */package chap04;// Queue.java// demonstrates queue// to run this program: C>java QueueApp////////////////////////////////////////////////////////////////class Queue {private int maxSize;private long[] queArray;private int front;private int rear;private int nItems;// --------------------------------------------------------------public Queue(int s) // constructor{maxSize = s;queArray = new long[maxSize];front = 0;rear = -1;nItems = 0;}// --------------------------------------------------------------public void insert(long j) // put item at rear of queue{if (rear == maxSize - 1) // deal with wraparoundrear = -1;queArray[++rear] = j; // increment rear and insertnItems++; // one more item}// --------------------------------------------------------------public long remove() // take item from front of queue{long temp = queArray[front++]; // get value and incr frontif (front == maxSize) // deal with wraparoundfront = 0;nItems--; // one less itemreturn temp;}// --------------------------------------------------------------public long peekFront() // peek at front of queue{return queArray[front];}// --------------------------------------------------------------public boolean isEmpty() // true if queue is empty{return (nItems == 0);}// --------------------------------------------------------------public boolean isFull() // true if queue is full{return (nItems == maxSize);}// --------------------------------------------------------------public int size() // number of items in queue{return nItems;}// --------------------------------------------------------------// ===========================================================// 編程作業 4.1public void display() {System.out.print("隊列為:");if (nItems == 0) {System.out.println("空。");return;}if (rear >= front) {for (int i = front; i <= rear; i++) {System.out.print(queArray[i] + " ");}} else {for (int i = front; i < maxSize; i++) {System.out.print(queArray[i] + " ");}for (int i = 0; i <= rear; i++) {System.out.print(queArray[i] + " ");}}System.out.println();}// ===========================================================} // end class Queue// //////////////////////////////////////////////////////////////public class QueueApp {public static void main(String[] args) {Queue theQueue = new Queue(5); // queue holds 5 itemstheQueue.display();theQueue.insert(10); // insert 4 itemstheQueue.insert(20);theQueue.insert(30);theQueue.insert(40);theQueue.remove(); // remove 3 itemstheQueue.remove(); // (10, 20, 30)theQueue.remove();theQueue.insert(50); // insert 4 more itemstheQueue.insert(60); // (wraps around)theQueue.insert(70);theQueue.insert(80);// =========================================theQueue.display();// =========================================while (!theQueue.isEmpty()) // remove and display{ // all itemslong n = theQueue.remove(); // (40, 50, 60, 70, 80)System.out.print(n);System.out.print(" ");}System.out.println("");} // end main()} // end class QueueApp// //////////////////////////////////////////////////////////////
package chap04;//======================================================================//編程作業 4.2class DuQueue {private int maxSize;private long[] queArray;private int front;private int rear;private int nItems;public DuQueue(int size) {maxSize = size;queArray = new long[maxSize];front = 0;rear = -1;nItems = 0;}public void insertLeft(long value) {if (front == 0) {front = maxSize;}queArray[--front] = value;nItems++;}public void insertRight(long value) {if (rear == maxSize - 1) {rear = -1;}queArray[++rear] = value;nItems++;}public long removeLeft() {long temp = queArray[front++];if (front == maxSize) {front = 0;}nItems--;return temp;}public long removeRight() {long temp = queArray[rear--];if (rear == -1) {rear = maxSize - 1;}nItems--;return temp;}public long peekLeft() {return queArray[front];}public long peekRight() {return queArray[rear];}public boolean isEmpty() {return nItems == 0;}public boolean isFull() {return nItems == maxSize;}public int size() {return nItems;}public void display() {System.out.print("隊列為:");if (nItems == 0) {System.out.println("空。");return;}if (rear >= front) {for (int i = front; i <= rear; i++) {System.out.print(queArray[i] + " ");}} else {for (int i = front; i < maxSize; i++) {System.out.print(queArray[i] + " ");}for (int i = 0; i <= rear; i++) {System.out.print(queArray[i] + " ");}}System.out.println();}}// ======================================================================public class DuQueueApp {public static void main(String[] args) {DuQueue theQueue = new DuQueue(5); // queue holds 5 itemsSystem.out.println("隊例是否為空白:" + theQueue.isEmpty());System.out.println("隊例是否為滿:" + theQueue.isFull());System.out.println("隊列的大小為:" + theQueue.size());theQueue.display();theQueue.insertRight(10); // insert 4 itemstheQueue.insertRight(20);theQueue.insertRight(30);theQueue.insertRight(40);System.out.println("隊列的大小為:" + theQueue.size());theQueue.display();theQueue.removeLeft(); // remove 3 itemstheQueue.removeLeft(); // (10, 20, 30)theQueue.removeLeft();System.out.println("隊列的大小為:" + theQueue.size());theQueue.display();theQueue.insertLeft(50); // insert 4 more itemstheQueue.insertLeft(60); // (wraps around)theQueue.insertLeft(70);theQueue.insertLeft(80);System.out.println("隊例是否為空白:" + theQueue.isEmpty());System.out.println("隊例是否為滿:" + theQueue.isFull());System.out.println("隊列的大小為:" + theQueue.size());theQueue.display();theQueue.removeRight(); // remove 3 itemstheQueue.removeRight(); // (10, 20, 30)theQueue.removeRight();System.out.println("隊列的大小為:" + theQueue.size());theQueue.display();} // end main()} // end class QueueApp
package chap04;//==========================================================//編程作業 4.3class StackY {private DuQueue stackQueue;public StackY(int size) {stackQueue = new DuQueue(size);}public void push(long value) {stackQueue.insertRight(value);}public long pop() {return stackQueue.removeRight();}public long peek() {return stackQueue.peekRight();}public boolean isEmpty() {return stackQueue.isEmpty();}public boolean isFull() {return stackQueue.isFull();}}// ==========================================================public class StackApp {public static void main(String[] args) {StackY theStack = new StackY(5); // make new stackSystem.out.println("Stack is Empty : " + theStack.isEmpty());System.out.println("Stack is Full : " + theStack.isFull());theStack.push(20); // push items onto stacktheStack.push(40);theStack.push(60);theStack.push(80);theStack.push(90);System.out.println("Stack is Empty : " + theStack.isEmpty());System.out.println("Stack is Full : " + theStack.isFull());while (!theStack.isEmpty()) // until it's empty,{ // delete item from stacklong value = theStack.pop();System.out.print(value); // display itSystem.out.print(" ");} // end whileSystem.out.println("");} // end main()} // end class StackApp
package chap04;// priorityQ.java// demonstrates priority queue// to run this program: C>java PriorityQApp////////////////////////////////////////////////////////////////class PriorityQ {// array in sorted order, from max at 0 to min at size-1private int maxSize;private long[] queArray;private int nItems;// -------------------------------------------------------------public PriorityQ(int s) // constructor{maxSize = s;queArray = new long[maxSize];nItems = 0;}// -------------------------------------------------------------// ==============================================================// 編程作業 4.4public void insert(long item) // insert item{queArray[nItems++] = item; // insert at 0} // end insert()// ==============================================================// 編程作業 4.4public long remove() // remove minimum item{int highPriority = 0;for (int i = 1; i < nItems; i++) {if (queArray[i] < queArray[highPriority]) {highPriority = i;}}long temp = queArray[highPriority];for (int i = highPriority; i < nItems - 1; i++) { // 數組後面部份往前移queArray[i] = queArray[i + 1];}nItems--;return temp;}// ==============================================================// 編程作業 4.4 //題目有 歧義// 方法一 :如果按插入的順序顯示public void display() {System.out.print("隊列為:");for (int i = 0; i < nItems; i++) {System.out.print(queArray[i] + " ");}System.out.println();}// 方法二:如果按按優先順序順序顯示public void display1() {long[] temp = new long[nItems];// 暫存資料表System.arraycopy(queArray, 0, temp, 0, nItems); // 複製到暫存資料表int out, in;for (out = 1; out < nItems; out++) {in = out;long t = temp[out];while (in > 0 && t < temp[in - 1]) {temp[in] = temp[in - 1];in--;}temp[in] = t;}System.out.print("隊列為:");for (int i = 0; i < nItems; i++) {System.out.print(temp[i] + " ");}System.out.println();}// ==============================================================// -------------------------------------------------------------public long peekMin() // peek at minimum item{return queArray[nItems - 1];}// -------------------------------------------------------------public boolean isEmpty() // true if queue is empty{return (nItems == 0);}// -------------------------------------------------------------public boolean isFull() // true if queue is full{return (nItems == maxSize);}// -------------------------------------------------------------} // end class PriorityQ// //////////////////////////////////////////////////////////////public class PriorityQApp {public static void main(String[] args) {PriorityQ thePQ = new PriorityQ(5);thePQ.insert(30);thePQ.insert(50);thePQ.insert(10);thePQ.insert(40);thePQ.insert(20);thePQ.display();//thePQ.display1();while (!thePQ.isEmpty()) {long item = thePQ.remove();System.out.print(item + " "); // 10, 20, 30, 40, 50} // end whileSystem.out.println("");} // end main()// -------------------------------------------------------------} // end class PriorityQApp// //////////////////////////////////////////////////////////////
package chap04;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;class Utility {public static String getString() throws IOException {// 接受鍵盤輸入字串InputStreamReader in = new InputStreamReader(System.in);BufferedReader bf = new BufferedReader(in);String s = bf.readLine();return s;}}// ===============================================================// 編程作業 4.5 沒有完全按照題目要求public class SuperMarket {private Queue[] queue = { null, new Queue(20), new Queue(20), new Queue(20), new Queue(20) }; // 4個顧客隊列// 類比收銀public void simulate() throws IOException {long id = 0; // 顧客編號boolean flag = true;while (flag) {System.out.println("請選擇事件:");System.out.print("0.有顧客進入某個隊列。");System.out.print("1.有顧客離開第1個隊例。");System.out.print("2.有顧客離開第2個隊例。");System.out.print("3.有顧客離開第3個隊例。");System.out.print("4.有顧客離開第4個隊例。");System.out.println("q.表示程式退出!");String s = Utility.getString();if (s.length() == 0) {// 直接輸入斷行符號continue;}char ch = s.charAt(0);switch (ch) {case '0':id++;insertQueue(id); // 顧客進入隊列displayQueue(); // 顯示隊列break;case '1':removeQueue(1); // 顧客離開隊列displayQueue(); // 顯示隊列break;case '2':removeQueue(2);displayQueue();break;case '3':removeQueue(3);displayQueue();break;case '4':removeQueue(4);displayQueue();break;case 'q': // 退出程式flag = false;System.out.println("byebye!");break;default:break;}}}// 從隊列中刪除顧客private void removeQueue(int queueId) {if (queue[queueId].size() == 0) {return;}long id = queue[queueId].remove();System.out.println("顧客" + id + "離開第" + queueId + "個隊列!");}// 把顧客插入到隊列public void insertQueue(long id) {int queueId = getMinQueueId();queue[queueId].insert(id);System.out.println("顧客" + id + "進入第" + queueId + "個隊例");}// 得到最小隊列的編號private int getMinQueueId() {int min = 1;for (int i = 2; i < 5; i++) {if (queue[i].size() < queue[min].size()) {min = i;}}return min;}// 列印顯示四條隊列public void displayQueue() {for (int i = 1; i < 5; i++) {System.out.print("第" + i + "個");queue[i].display();}System.out.println();}public static void main(String[] args) throws IOException {SuperMarket sm = new SuperMarket();sm.simulate();}}