E2, 采用栈的方法,为下面的说明编写一个函数 copy_satck:
Error_codecopy_stack(stack &dest,Stack &source);
前置条件:无。
后置条件:Stack dest已经成为 Stack source 的一个完全副本,而source未被改变。
如果检测到错误,则返回一个合适的代码,否则返回success。
(b 使用Stack方法和一个临时的Stack,从Stack source中抽取元素并将每个元素加入到Stack dest 中,并回复Stack source。
Error_code Stack::copy_stack(Stack&dest,Stack &source)
/*Pre:None.
Post:Stack dest has become an exact copy of Stack source;source
isunchanged.If an error is deteced,an apporpriate code is returned.*/
{
Error_code outcome = success;
Stack T; //临时的Stack
Stack_entry item; //临时储存元素
while(outcome == success&&!source.empty())
{
outcome = source.top(item);
outcome = source.pop();
if(outcome == success)
outcome = T.push(item);
}
while(outcome == success&&!T.empty())
{
outcome = T.top(item);
outcome = T.pop();
if(outcome == success)
{
outcome = dest.push(item);
outcome = source.push(item);
}
}
return outcome;
}