演算法第四版習題1.3.14和1.3.19(Java實現)
阿新 • • 發佈:2018-11-26
近來在啃資料結構與演算法,歡迎交流。
1.3.14:用可變長度的陣列實現佇列(FIFO)
- 資料結構ResizingArrayQueueOfStrings 的實現:
public class ResizingArrayQueueOfStrings { String[] arr; int N; public ResizingArrayQueueOfStrings(int cap) { arr = new String[cap]; } public void queue(String str) { if (N + 1 == arr.length) resize(arr.length * 2); for (int i = N; i >= 0; i--) { arr[i + 1] = arr[i]; } arr[0] = str; N++; } public String dequeue() { String s = arr[--N]; if (N > 0 && N == arr.length / 4) resize(arr.length / 2); return s; } private void resize(int max) { String[] arrnew = new String[max]; for (int i = 0; i <= N; i++) { arrnew[i] = arr[i]; } arr = arrnew; } public boolean isEmpty(){ return N == 0; } public int size(){ return N; } }
- client code(書上似乎稱作:用例程式碼,翻譯有點拗口喲)
public class Ex1_3_14_Client { public static void main(String[] args) { ResizingArrayQueueOfStrings qos = new ResizingArrayQueueOfStrings(5); qos.queue("Baba "); qos.queue("black "); System.out.println("size1:"+qos.size()); qos.queue("sheep "); qos.queue("have "); System.out.println("size2:"+qos.size()); qos.queue("you "); qos.queue("any "); qos.queue("wood "); qos.queue("?"); System.out.println("size3:"+qos.size()); String s = ""; while (!qos.isEmpty()) { s += qos.dequeue(); } System.out.println(s); } }
- 測試結果:
size1:2
size2:4
size3:8
Baba black sheep have you any wood ?
Baba black sheep have you any wood ?不知道有多少人知道這首朗朗上口的英文兒歌呢~
1.3.19:在以連結串列為基礎的棧中新增一個方法,使之可以進行頭尾“壓棧”、頭尾“彈棧”並返回彈出的元素:
- 資料結構MyLinkedlist實現:
public class MyLinkedlist<Item> { private int N; private Node first; private Node last; private class Node{ Node next; Item item; } public void push(Item item){ Node oldfirst = first; first = new Node(); first.item = item; if (N == 0){ first.next = null; last = first; } else first.next = oldfirst; N++; } public void pushBottom(Item item) { Node oldlast = last; last = new Node(); last.item = item; last.next = null; if (N == 0) first = last; else oldlast.next = last; N++; } public Item pop(){ Item item = first.item; first = first.next; N--; return item; } public Item popBottom(){ Item item = last.item; Node temp = first; for (int i = 1; i < N-1; i++) { temp = temp.next; // 第n-1個結點 } last = temp; last.next = null; N--; return item; } public int size(){ return N; } }
- client code:
public class Ex1_3_19 {
public static void main(String[] args) {
MyLinkedlist<String> mll = new MyLinkedlist<>();
mll.push("wood ");
mll.push("any ");
mll.push("you ");
mll.push("have ");
mll.pushBottom("? ");
String str = "";
int len = mll.size();
for (int i = 0; i < len; i++) {
str += mll.popBottom();
// str += mll.pop();
}
System.out.println(str);
}
}
- 測試結果:
popBottom:
? wood any you have
pop:
have you any wood ?