作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正忙于单链表的实现,并且有 2 个函数:insert_back
和 insert_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 一起使用一个 while
或 for
循环?
我还看到参数 int pos
是 int
。我应该使用 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/
我是一名优秀的程序员,十分优秀!