P64 Exercise 2.2
E2:
(a)问题:
simply use an assignment statement:dest=source;
答案:
Error_code copy_stack(Stack &dest,&source)
{
Dest=source;
return success;
}
(b)问题:
Use the Stack methods and a temporary Stack to retrieve entries from the Stack source and add each entry to the Stack dest and retore Stack source.
答案;
Error_code copy_stack(Stack &dest,Stack &source)
{
Erroe_code detected=success;
Stack temp;
Stack_entry item;
While (detected==success&&!source.empty()}{
Detected=source.top(item);
Detected=source.pop();
if(detected==success)detected=temp.push(item);
}
While(detected==succes&&!temp.empty()}{
detected=temp.top(item);
detected=temp.pop();
if(detected==success)detected=source.push(item);
if(detected==success)detected=dest.push(item);
}
return detected;
}
(c)问题:
Write the function as a friend^2 to the class Stack .Use the private data members of the Stack and write a loop that copies entries from source to dest.
答案:
Error_code copy_stack(Stack&dest,Stack &source)
{
dest.count=source.count;
for(int i=0;i<source.count;i++)
Dest.entry[i]=source.entry[i];
return success;
}
问题:
1.哪一个程序是最容易写的?如果栈快满了哪一个运行最快?如果一个栈接近空那个运行最快?如果可以改变,哪一个是最好的方法?那一个函数可以将source作为常量引用传递?
答案:第一个是写的最容易的,而且它是运行最快的当栈接近满时,编译器会使机器代码复制进入比第三种环状方法更快,如果栈接近于空,那么第三种方法将是最快的,他只是复制已占用的进入,然而,在数组中第一种方法复制所有的位置,已占用的或未被占用的,因为所有的功能都要被访问,第二个或许运行的慢一些,如果栈接近于空那么,它会打败第一种方法,如果改变,第二个是独立实现的并且是最好的,如果是联合的实现第一个将会失败,他只能设置变量资源和指向同一个节点,如果没有栈的复制就会自己生成,资源和dest会成为相同的栈,改变一个就会改变另一个。
P92 Exercise3.3
E7 问题:
重新编写课本中队列处理的方法,使用一个标志而不是保持队列中元素个数的技术来指示满队列。
答案:
The class definition for this queue implementation is as follows.
const int maxqueue=10;
class Queue{
Public:
Queue();
Bool empty()const;
Error_code serve();
Error_code append(const Queue_entry &item);
Error_code retrieve(Queue_entry&item)const;
Protected:
int front ,rear;
Queue_entry entry[maxqueue];
bool is_empty;
};
The method implementations follow.
Queue::Queue()
{
rear=-1;
front=0;
is_empty=true;
}
Bool Queue::empty()const
{
return is_empty;
}
Error_code Queue::append(const Queue_entry &item)
{
if(!empty()&&(rear+1)%maxqueue==front)return overflow;
is_ empty=false;
Rear=((rear+1)==maxqueue)?0:(rear+1);
Entry[rear]=item;
return success;
}
Error_code Queue;:retrieve(Queue_entry&item)const
{
if((empty())return underflow;
item=entry[front];
Return success;
}