Problem 1: Client-side vs. Implementation-side:
a) as the implementers去实现reverse操作,所以我们可以使用类中private的东西
template <typename Type>
void Stack<Type>::reverse(){
for(int lh = 0, rh = elems.size() -1; lh < rh; rh--, lh++)
{
Swap(elems[lh], elem[rh]); //还有这种操作。。。
}
}
b) as a cilent, 当然是调用stack实现功能
void reverse(Stack<Type> & s) //可以看出这是类外使用类,即是作为client使用类
{
Stack<Type> t;
while(!s.isEmpty)
{
t.push(s.pop()); //一出一入实现转置
}
s = t;
}
Problem 2: Template Class Conversion
改成模版类,照着套路来就是
template<typename Type>
class Mob{
public:
Mob();
void enqueue(Type newElem);
Type dequeue;
int size();
private:
Vector<Type> elems;
};
template<typename Type> //每个函数前都要加这个,老是忘了
void Mob<Type>::enqueue(Type newElem){
elems.add(newElem);
}
template<typename Type>
Type Mob<Type>::dequeue()
{
int elemNum = RandomInteger(0, elems.size()-1);
Type value = elems[elemNum];
elems.removeAt(elemNum);
return value;
}
Problem 3: Big-O Detective
pass
Problem 4: Deques
使用双向链表,实现队列队首队尾队的操作。
Problem 5: Stutter
链表加东西的操作,第一反应用是递归,好像for也挺简单的,那下题再用递归写
void Stutter(Node* list)
{
for(Node* curr = list; curr! = NULL; curr = curr->next)
{
Node* stuttered = new Node; //注意了 要用new
stuttered->value =curr->value;
stuttered->next = curr->next;
curr->next = stuttered;
curr = stuttered; //简单的指针操作,唯一需要注意的是顺序问题,因为curr->next需要改变,所以需要先用它
}
}
Problem 6: RemoveDuplicates (a.k.a. Unstutter)
链表删除操作,比较简单,核心就是一条代码,注意别忘记删除不要的链表指针,反正我是忘了。
void Remove(Node* list)
{
Node* curr = list; //都需要这一步,保证头指针不丢失
if(curr->next == NULL)
return;
if(curr->value == curr->next->value)
{
Node* duplicate = cur->next;
curr->next = curr->next->next //核心
delete duplicate; //解放删除的指针
}
return(curr->next);
}