gpt4 book ai didi

根据位置从链表创建子列表?

转载 作者:行者123 更新时间:2023-11-30 16:56:47 26 4
gpt4 key购买 nike

我正在尝试输入一个需要 2 个链表的函数。第一个具有要打印的值,第二个具有要打印的链表值的位置。它给了我一个错误,我将其作为注释放入代码中。

结构体

typedef int Item;
typedef struct node_struct * link;
typedef struct list_struct * list;

struct node_struct {
Item item;
link next;
};

struct list_struct {
link first;
int length;
};

功能:

list sublist(list A, list pos_list) {
link tempOne;
link tempTwo;
link node = malloc(sizeof *node);
tempOne = pos_list->first;
tempTwo = A->first;
int counter;
while(tempOne->next != NULL)
{
counter = 0;
while(counter < tempOne->item && tempOne->next != NULL)
{
tempTwo = tempTwo->next;
counter = counter+1;
}
node->item = tempTwo->item; //EXC_BAD_ACCESS code:1
node = node->next;
tempTwo = A->first;
tempOne = tempOne->next;
counter = 0;
}
return node;

最佳答案

代码中有很多不好的做法,这使得您和我们理解(从而调试和维护)此类代码都非常困难。

  • 当您无意隐藏指针后面的实际数据时,您正在创建指针 typedef
  • 您正在使用相同的数据类型创建职位链接列表和数据链接列表。我知道在你的情况下两者都是 int,但不要使用误导性的 typedef int Item 并简单地坚持使用 int
  • tempOnetempTwo 在这种情况下可能是最糟糕的命名选项,不仅用于调用具有非直观名称(如 temp)的变量,但还将第一个参数调用为 Two ,将第二个参数调用为 One - 尽可能违反直觉
  • 我可以看到您使用两种不同结构的情况 node_struct (坦率地说,我将其称为 node),并且 list_struct 请参阅 node_struct 注释),但在本示例中,您不需要 list_struct,它只会给代码增加更多困惑。
  • 您确实应该在单独的函数中执行“查找”工作(内部 for 循环),这样您就可以轻松处理错误,并且不会将内部循环与外部循环混淆

有了这个,您还没有指定 pos_list 是否实际上包含相对位置(相对于前一个位置的位置)或绝对位置(如数组索引)。我假设它是绝对位置。

执行node = node->next;后,您需要再次malloc它。或者更确切地说,只是在 node->item = tempTwo->item; 行上使用它之前对其进行 malloc,并删除循环外部的 malloc

我手边没有c编译器,所以无法测试它。但我没有看到任何其他问题

编辑

我注意到子列表的返回值始终只是最后一个节点,而不是链表中的第一个节点 - 这显然也是一个问题。

下面是我如何编写这段代码。请记住,这不是经过调试和测试的代码,而只是想法的表达(如果您愿意的话,可以是初稿)

typedef struct Node_ Node;

struct Node_ {
int Item;
Node* Next;
};

Node* GetNodeAt(Node *dataList, int indx) {
for (int i = 0; i < indx && dataList != NULL; ++i)
dataList = dataList->Next;
return dataList;
}

Node* SubList(Node *dataList, Node *posList) {
Node* origDataList = dataList;

Node *currentRetNode = malloc(sizeof(Node));
Node *prevRetNode = NULL, *returnList = currentRetNode;

while (posList->Next != NULL) {
// Find the node in dataList
Node *node = GetNodeAt(dataList, posList->Item);

// create/manage the linked list to be returned
prevRetNode = currentRetNode;
currentRetNode->Next = malloc(sizeof(Node));
currentRetNode->Item = node->Item;
currentRetNode = currentRetNode->Next;

posList = posList->Next; // move to the next index
}

free(currentRetNode);

if (prevRetNode == NULL)
returnList = NULL;
else
prevRetNode->Next = NULL;

return returnList;
}

关于根据位置从链表创建子列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39810460/

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