[我的档案在这里(链接删除)]
我的复制功能不会复制整个列表。
根据@Mat的要求,这里是“复制”功能,但您仍需要阅读文件的其余部分以了解我的结构。
Line copyLineText(Line l){
Line newl = malloc (sizeof( struct node ));
checkMalloc(newl,"copyLineText");
newl->length = l->length;
newl->buffer = malloc((newl->length)* sizeof(char));
checkMalloc(newl->buffer,"copyLineText buffer");
strncpy(newl->buffer, l->buffer, newl->length);
return newl;
}
/* Copy the lines between and including 'from' and 'to' of the textbuffer
* 'tb'.
*
* - The result is a new textbuffer (much as one created with newTB()).
* - The textbuffer 'tb' will remain unmodified.
* - The program is to abort() with an error message if 'from' or 'to' is out
* of range.
*/
TB copyTB (TB tb, int from, int to){
if (from > to || from < 0 || to >= tb->numLines){
printf("Error: the from to is out of range\n");
abort();
}
Line line = tb->begin;
while(line->linePosition != from){
line = line->next;
}
TB tbCopy = malloc (sizeof( struct textbuffer ));
Line last = NULL, curr = line, currCopy;
while( curr != NULL && (curr->linePosition != to + 1) ){
currCopy = copyLineText(curr);
if(last == NULL){
tbCopy->begin = currCopy;
}
currCopy->prev = last;
if(last != NULL){
last->next = currCopy;
//printf("362debug: last->next = currCopy\n");
}
last = curr;
//printf("364debug: %d\n",curr->linePosition);
curr = curr->next;
}
currCopy->next = NULL;
tbCopy->end = currCopy;
tbCopy->numLines = to - from + 1;
return tbCopy;
}
如果您运行我的代码,您会看到:
tb2:2 lines
abcde
fg
tb2copy:2 lines
abcde
通过这个简单的测试,我的函数生成的副本比原始结构少一行。
答案 0 :(得分:0)
在问题c的第161行,当您复制链接列表时,您将原始链接列表中的元素分配给last
,而不是分配前一个来自新创建的列表。
从以下位置更改该行:
last = curr;
为:
last = currCopy;