PrincetonAlgorithm I - Assignment2 Deques and Randomized Queues
阿新 • • 發佈:2018-05-12
creat 時間 nta AD sig rate turn insert lec
Programming Assignment2 - Deque and Randomized Queues Review
Assignment Specification
課程筆記
Subtext: Modular Programming
- Stacks and Queues are fundamental data types
- Value: collection of objects
- Basic Operation: insert, remove, iterate.
- Difference: which item do we move? -> Stack: LIFO(last in first out) Queue: FIFO(first in first out)
- Client, implementation, interface
- Client: program using operations defined in interface
- Implementation: actual code implementing operations
- Interface: description of data type, basic operations
Stack Programming API:
public class StackOfStrings
StackOfStrings() //create an empty stack
void push(String item) //insert a new string onto stack
String pop() //remove and return the string most recently added
boolean isEmpty() //is the stack empty?
linked-list implementation
//Attention: Stack have only one exit -> only one pointer is enough
/*Corner Cases:
client add a null item -> IllegalArgumentException
remove() from empty stack -> NoSuchElementException
*/
public class StackOfStrings {
private Node first;
private class Node {
String item;
Node next;
}
public boolean isEmpty() {
return first == null;
}
public StackOfStrings {
Node first = null;
}
public void push(String item) {
//Improve: add exception to deal with invalid operation
Node oldfirst = first;
first = new Node(); //Attention: must craete a new instance here
first.item = item;
first.next = oldfirst;
}
public String pop() {
String item = first.item;
first = first.next;
return item;
}
在寫代碼的過程當中,心裏需要有轉換角色的意識,當你在實現一個API的時候,需要考慮的是
* 實現某個方法所要使用的數據結構,
* 調用方法 or 自己寫方法,
* API的性能要求 -> 使用哪種算法可以滿足要求 查找,插入,刪除 時間 + 空間
Stack的鏈表實現
Stack的數組實現(resize array)
Queue的鏈表實現
Queue的數組實現(resize array)
對於雙向隊列的理解有誤,導致錯誤實現。
雙向對別不應當是兩個隊列的水平疊加,見figure 1
作業總結:
- 對於文件的讀寫基本操作命令不夠熟悉
- 對於問題的定義 出現了沒有搞清楚題目要求的現象,包括Deque的基本操作 以及Permutation 類當中,應當是讀取全部數據,輸出k個數據,而不是讀取k個數據,輸出全部數據的問題
PrincetonAlgorithm I - Assignment2 Deques and Randomized Queues