gpt4 book ai didi

更改函数签名及其参数: list* to node*

转载 作者:行者123 更新时间:2023-11-30 16:41:38 24 4
gpt4 key购买 nike

我正在创建一个程序,该程序反转由单链接列表表示的单词的非元音序列,没有头和哨兵。换句话说,列表中的每个节点都有一个字母字段。我的程序必须反转此列表中的非元音序列(空格、辅音、点和逗号),而不修改原始列表。

算法本身已准备就绪并可以运行。我的问题在于如何将LIST*函数转换为NODE*类型函数。例如,LIST* toCloneList(LIST* l ) 必须是 NODE* toCloneList(NODE* p) 并且 void demo(LIST* answer) 必须是 NODE*decode(NODE*answer) .

LIST* toCloneList(LIST* l){
LIST* answer = malloc(sizeof(LIST));

NODE *current = l->first;
NODE *previous = NULL;

while(current){
NODE *newnd = (NODE*) malloc(sizeof(NODE));
newnd->letter = current->letter;
newnd->next = NULL;

if (previous == NULL){
answer->first = newnd;
}
else {
previous->next = current;
}

previous = newnd;
current = current->next;
}

return answer;
}

void invert(LIST* answer){

NODE* actual = answer->first;
answer->first = NULL;

while (actual != NULL){
NODE* current = actual;
actual = actual->next;


current->next = answer->first;
answer->first = current;
}
}

void decode(LIST* answer) {
NODE* fNv = NULL; //first non-vowel found
NODE* lNv = NULL; //last non-vowel found

NODE* current = answer->first;
NODE* previous = NULL;

while (current != NULL) {

/* While current points to a non-vowel. */
if (checkSequence(current)) {
fNv = current;

/* Searches the last non-vowel case in the list. */
while (current->next != NULL && checkSequence(current->next)) {
current = current->next;
}

/* When the next letter is a vowel, then the end of the non-vowel sequence is reached. */
lNv = current;

/* If there is a non-vowel sequence, in other words, fNv and lNv do not point to the same element, then the position change must be performed. */
if (fNv != lNv) {
/* Calls a recursive function to perform the change of positions without having to create a new list. */

NODE* k = lNv->next;

invertNvs(fNv->next, fNv, lNv);

fNv->next = k;

if (previous == NULL){
answer->first = lNv;
}
else {
previous->next = lNv;
}

current = fNv;
}
}
previous = current;
current = current->next;
}
}

该程序应该适用于这样的调用:

NODE* test = null;
test = decode(p);

完整代码-https://repl.it/LAuW/0

最佳答案

您根本不需要LIST,只需使用NODE即可。这使您的代码变得更加容易。

但是,或者,如果你真的愿意,你可以引入一堆“薄 wrapper ”,有点

void decodeList(LIST *l)
{
if (l != 0)
decodeNode(l->first);
}
顺便说一句。另外,在切换到 C++ 的情况下,您将有机会使用内联函数和重载函数,这使其看起来更自然,例如:

inline void decode(LIST& l) { decode(l.first); }

不幸的是,使用纯 C 语言您无法使用重载,因此您必须为函数使用不同的名称。

关于更改函数签名及其参数: list* to node*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46187786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com