我对单向链表,这是我不能在其他问题找到答案一个非常简单的问题。单链表 - Visual C
这是我的代码:
#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;
}
}
现在,我一直在告诉我,我需要创建一个功能或我的外接功能内的情况下,如果正在创建一个新的列表以不同方式做一些事情。换句话说,当列表是空的,并且第一个元素被添加到它时,它需要与填充列表正在接收前面的另一个节点时不同。我发现这样的代码在网上的一个例子:
# // 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,你应该'返回'。你不需要打印新的节点,只需使用指向头部的指针就足够了。内存泄漏 –
您的printList函数有一个错误:它malloc一个新的临时节点,然后立即用头指针覆盖malloc'd指针,从而泄漏分配的节点。在这种情况下分配是不必要的。 –
啊!你是对的!谢谢! – seyelent