网站大量收购独家精品文档,联系QQ:2885784924

(精品课件)第四次chapter4作业(10.18评讲).doc

(精品课件)第四次chapter4作业(10.18评讲).doc

  1. 1、本文档共8页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
(精品课件)第四次chapter4作业(10.18评讲)

P130 E2 E2. Consider a linked stack that includes a method size. This method size requires a loop that moves through the entire stack to count the entries, since the number of entries in the stack is not kept as a separate member in the stack record. Write a method size for a linked stack by using a loop that moves a pointer variable from node to node through the stack. Answer int Stack :: size() const /* Post: Return the number of entries in the Stack. */ { Node *temp = top_node; int count = 0; while (temp != NULL) { temp = temp -next; count++; } return count; } Consider modifying the declaration of a linked stack to make a stack into a structure with two members, the top of the stack and a counter giving its size. What changes will need to be made to the other methods for linked stacks? Discuss the advantages and disadvantages of this modi?cation compared to the original implementation of linked stacks. Answer 构造函数需添加将count初始化为0的语句。 empty函数和size函数只要根据count返回相应结果。 成功的push操作应使count增1 成功的pop操作应使count减1 优点:可使链栈类与顺序栈类一致。 减少size方法的运行时间。 缺点:增加额外的变量和额外的代码。 是否添加count,取决于size方法的调用频率。 P137 4.3 E2 E2. What is wrong with the following attempt to use the copy constructor to implement the overloaded assignment operator for a linked Stack? void Stack :: operator = (const Stack original) { Stack new_copy(original); top_node = new_copy.top_node; } How can we modify this code to give a correct implementation? Answer The assignment top_node = new_copy.top_node; leaves the former nodes of the left hand side of the assignment operator as garbage.应该回收的空间没回收,结果丢了变成垃圾! Moreover, when the function ends, the statically allocated Stack new_copy will be destructed, this will destroy the newly assigned left hand side of the assignment operator. 把需要赋值不该回收的空间回收了。 We can avoid both problems by swapping the pointers top_node and new_copy.top_node as in the following. //用书上的方法也可以 void Stack :: operator = (const Stack original) /* Post: The Stack is reset as a copy of Stack original. */ { Stack n

文档评论(0)

yan698698 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档