【发布时间】:2011-07-27 15:19:19
【问题描述】:
我有一个关于单链表的非常简短的问题,我在其他问题中找不到答案。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
void add(int data);
void printList();
struct node
{
int data;
struct node * link;
};
struct node * head = NULL;
main()
{
char c;
while ((c = getchar()) != 'q')
{
if (c == 'a')
{
int temp;
printf("data: ");
scanf("%d", &temp);
add(temp);
}
if (c == 'p')
printList();
}
}
void add(int data)
{
struct node * temp = (struct node *) malloc(sizeof(struct node));
if (temp == NULL)
fprintf(stderr, "error");
temp->link = head;
temp->data = data;
head = temp;
}
void printList()
{
struct node * temp = (struct node *) malloc(sizeof(struct node));
if (temp == NULL)
fprintf(stderr, "error");
temp = head;
while (temp != NULL)
{
printf("%d", temp->data);
temp = temp->link;
}
}
现在,有人告诉我,我需要在我的 add 函数中创建一个函数或一个场景,如果正在创建一个新列表,它会做一些不同的事情。换句话说,当列表为空并且第一个元素被添加到其中时,它需要与填充列表在前面接收另一个节点时不同。我在网上找到了这样的代码示例:
# // Adding a Node at the Beginning of the List
#
# void addBeg(int num)
# {
# struct Node *temp;
#
# temp=(struct Node *)malloc(sizeof(struct Node));
# temp->Data = num;
#
# if (Head == NULL)
# {
# //List is Empty
# Head=temp;
# Head->Next=NULL;
# }
# else
# {
# temp->Next=Head;
# Head=temp;
# }
# }
如您所见,如果列表为空,则填充头节点。
我的代码工作正常,但我想知道在处理空头情况方面我是否忽略了一些东西。
非常感谢!
【问题讨论】:
-
您的 add() 函数可以工作,但如果 malloc 失败,它会出现段错误。如果
temp == NULL,你应该return。您也不需要在 print 中 malloc 一个新节点,只需使用指向 head 的指针就足够了。内存泄漏 -
您的 printList 函数有一个错误:它 malloc 一个新的临时节点,然后立即用头指针覆盖 malloc 的指针,从而泄漏分配的节点。在这种情况下,分配是不必要的。
标签: c