gpt4 book ai didi

c - 如何在一个循环中组合序列号和null?

转载 作者:行者123 更新时间:2023-11-30 15:48:04 25 4
gpt4 key购买 nike

我正忙于单链表的实现,并且有 2 个函数:insert_backinsert_after

以下是它们的列表:

void insert_back(int data)
{
node *temp1;

temp1 = (node*)malloc(sizeof(node));
temp1 = head;

while (temp1->next != NULL) {
temp1 = temp1->next;
}

node *temp;

temp = (node*)malloc(sizeof(node));
temp->data = data;
temp->next = NULL;
temp1->next = temp;
}

void insert_after(int pos, int data)
{
node *temp1;

temp1 = (node*)malloc(sizeof(node));
temp1 = head;

for (int i = 1; i < pos; i++) {
temp1 = temp1->next;

if (temp1 == NULL) {
return;
}
}

node *temp;

temp = (node*)malloc(sizeof(node));
temp->data = data;
temp->next = temp1->next;
temp1->next = temp;
}

如您所见,它们几乎相同,对于插入回,我想编写 insert_after(null, 10)。我可以通过添加 if 条件并选择其中一个循环来解决它,但这不是我的目标。

是否可以以某种方式对序列号和 null 一起使用一个 whilefor 循环?

我还看到参数 int posint。我应该使用 0 而不是 null 吗?

最佳答案

您在以下几行中不必要地分配了内存。

temp1 = (node*)malloc(sizeof(node));
temp1 = head;

当您覆盖 temp1 中返回的地址时,分配的内存将会泄漏。 。您只需要temp1遍历列表,因此也不需要分配任何节点本身。 temp1可以指向任意节点。

我冒昧地从头开始编写了一个例程,一次性完成这两件事。如果pos < 0它将将该元素添加到列表的末尾,否则它将添加到第 pos-th 元素之后,其中第一个元素对应于 pos == 1 。如果pos == 0该元素被添加到列表的开头。

还有一个小main添加以测试例程。 new_node添加了测试内存是否耗尽的功能。

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

typedef struct node
{
struct node * next;
int data;
} node;

node * head = NULL;

node * new_node(void)
{
node * result = malloc(sizeof(*result));
if (result == NULL)
{
fprintf(stderr, "Out of memory.\n");
exit(10);
}
return result;
}

void insert_after(int pos, int data)
{
node *walk, * prev;
int i;

prev = NULL;
walk = head;

for (i = 0; walk != NULL && i != pos; i++)
{
prev = walk;
walk = walk->next;
}

if (i != pos && pos > 0)
{
fprintf(stderr, "Location not found.\n");
exit(9);
}
else
{
walk = new_node();
walk->data = data;

if (prev == NULL)
{
walk->next = head;
head = walk;
}
else
{
walk->next = prev->next;
prev->next = walk;
}
}
}

int main(void)
{
int i;
node * wlk;

for (i = 0; i < 10; i++)
{
insert_after(-1, i);
}
for (i = 0; i < 10; i++)
{
insert_after(3, i+10);
}

for (wlk = head; wlk != NULL; wlk = wlk->next)
{
printf("%d\n", wlk->data);
}
return 0;
}

关于c - 如何在一个循环中组合序列号和null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17047957/

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