标签:课程笔记 client string recently exception create link 调用 空间
Subtext: Modular Programming
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
作业总结:
PrincetonAlgorithm I - Assignment2 Deques and Randomized Queues
标签:课程笔记 client string recently exception create link 调用 空间
原文地址:https://www.cnblogs.com/kong-xy/p/9028179.html