gpt4 book ai didi

c - 链表删除节点

转载 作者:行者123 更新时间:2023-12-02 08:37:53 27 4
gpt4 key购买 nike

所以我试图实现一个从链表中删除节点的函数。

这是我的主要内容:

int main(void)
{
NODE* first = generateNodes(5);
NODE* jank = getNode(first, 2);
deleteNode(first,2);
printf("Length of Node List: %d\n",getNodeListLength(first));
printf("First Node: %d\n",first -> pos);
printf("Jank Node: %d\n",jank -> pos);
return 0;
}

这是我的输出:

Length of Node List: 2
First Node: 0
Jank Node: 2

输出应该是(因为在 main() 中我删除了 jank,并将链表的大小减少了一个):

Length of Node List: 4
First Node: 0
Jank Node: NULL

这是我的全部源代码:

#include <stdio.h>
#include <stdlib.h>

/* NODE STRUCTURE */

typedef struct node{

char* thing;

int pos; /* Index of node */
struct node* next; /* Pointer to next node */

} NODE;

/* Generates a single node */
NODE* generateNode();

/* Generates linked nodes and returns the first node */
NODE* generateNodes(int num);

/* Gets a node at a certain index */
NODE* getNode(NODE* start, int index);

/* Returns the length of a list of nodes */
size_t getNodeListLength(NODE* start);

/* Removes a node at a certain index */
NODE* deleteNode(NODE* start, int index);

int main(void)
{
NODE* first = generateNodes(5);
NODE* jank = getNode(first, 2);
deleteNode(first,2);
printf("Length of Node List: %d\n",getNodeListLength(first));
printf("First Node: %d\n",first -> pos);
printf("Other Node: %d\n",jank -> pos);
return 0;
}

NODE* generateNode()
{
return (NODE*) malloc(sizeof(NODE));
}

NODE* generateNodes(int num)
{
NODE* one = generateNode();
NODE* cpy = one;

int i;

for(i = 0; i < num - 1; i++)
{

NODE* next = generateNode();
cpy -> next = next;
cpy -> pos = i;
cpy = next;

}

cpy -> pos = i;
cpy -> next = NULL;

return one;
}

NODE* getNode(NODE* start, int index)
{
int i;
for(i = 0; i < index; i++)
{
start = start -> next;
}
return start;
}

size_t getNodeListLength(NODE* start)
{
size_t i;
while(start -> next != NULL)
{
start = start -> next;
i++;
}
return i - 1;
}

NODE* deleteNode(NODE* start, int index)
{
if(index > 0)
{
NODE* f = getNode(start,index - 1);
NODE* l = getNode(start,index + 1);
NODE* d = getNode(start,index);
f -> next = l;
free(d);
return start;
}
if(index == 0)
{
NODE* up = start -> next;
free(start);
return up;
}
if(index + 1 == getNodeListLength(start))
{
NODE* r = getNode(start,index);
NODE* c = getNode(start,index - 1);
c -> next = NULL;
free(r);
return start;
}
}

我哪里出错了?

最佳答案

我注意到您在 getNodeListLength 中的 size_t i 未初始化为任何值 - 这可能是意外大小报告的来源。

此外,您从列表中删除了 jank,但您的 jank 指针仍指向该节点(即使它已被 free 'd) - 这意味着在访问不再属于您的内存之后使用 jank!

关于c - 链表删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19440660/

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