所以我试图实现以下目标:;
// Destructive Abstract data type ilist
struct ilist_ADT;
typedef struct ilist_ADT *ilist;
// prototype for secret implementation
// do not rely on ilist being a pointer
ilist iempty();
// returns an empty ilist
int iempty_huh(ilist il);
// returns 1 (true) if il is empty
// returns 0 (false) if il is not empty
int ifirst(ilist il);
// returns the first element in il
// il must not be empty
ilist icons_destroy(int in, ilist il);
// returns an ilist with in added as the first element of il
// references to il cease to be valid ilists
// the result must eventually be consumed by one of:
// icons_destroy, irest_destroy, idelete
ilist irest_destroy(ilist il);
// modifies il to remove the first element, and returns the modified ilist
// frees the memory associated with the first element
// references to il cease to be valid ilists
// the result (if non-empty) must eventually be consumed by one of:
// icons_destroy, irest_destroy, idelete
ilist icopy(ilist il);
// returns a new copy of il that continues to be a valid
// ilist with the same elements even when il is destroyed
// the result must eventually be consumed by one of:
// icons_destroy, irest_destroy, idelete
int ilength(ilist il);
// computes the number of elements in il
void idelete(ilist il);
// frees the storage for ilist
// all further references to il become invalid
// NOTE: every ilist created by icons_destroy or
// irest_destroy or icopy must eventually be destroyed
// by being consumed by icons_destroy or
// irest_destroy or idelete
我首先关注图标,我有一个非破坏性图标,例如:
ilist icons(int in, ilist il) {
ilist r = malloc(sizeof(struct ilist_ADT));
r->first = in;
r->rest = il;
r->length = 1 + ilength(il);
return r;
}
我该怎么做才能符合实际情况呢?换句话说,我如何使它具有破坏性?
最佳答案
“破坏性”是指允许修改函数(或oop方法中的接收器)的参数。非破坏性函数表示它不修改其参数,而是返回修改后的副本。允许破坏性函数的优点是,您不必创建该副本,因此通常需要较少的malloc(在本例中,数量相同)。
在icons
的实现中,您可以看到con'ing a entry使原始的ilist il
保持一个有效的未修改列表!:任何使用ilist il
的人都不会注意到您做了什么(当然,这只适用于单独链接的列表)。
破坏性实现首先允许您修改参数,但它也意味着您应该以有意义的方式修改参数:您应该修改它,以便仍具有对原始ilist il
引用的人能够看到您的修改。你可以这样做:
// observation: the names are not the best, i would call it destructiveICons
// (and ->first should be called ->value)
ilist icons_destroy(int in, ilist il) {
ilist second = malloc(sizeof(struct ilist_ADT));
second->length = il->length
second->first = il->first
second->rest = il->rest;
il->length += 1;
il->rest = second;
il->first = in;
return il;
}
现在,持有
ilist il
引用的其他人将看到新的第一个元素后面跟着旧的前一个元素。关于c - 列表-C(作业),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9243475/