这是一个简单的程序,用于插入节点并将其显示在链接列表中,从而绕过该函数的头节点。这是更大程序的一部分,但我无法对其进行故障排除。每次显示节点时,它说链接列表为空。
#include <stdio.h>
#include <stdlib.h>
struct nodes
{
int data;
struct nodes *next;
};
typedef struct nodes *node;
void InsertFront(node head)
{
int num;
node temp = malloc(sizeof(node));
printf("Enter The Value Of Node\n");
scanf("%d", &num);
temp->data = num;
if (head == NULL)
{
temp->next = NULL;
head = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void Display(node head)
{
node q;
if (head == NULL)
{
printf("Linked List Seems To Be Empty");
}
else
{
q = head;
while (q != NULL)
{
printf("%d -> ", q->data);
q = q->next;
}
}
}
void main()
{
node head;
head = NULL;
InsertFront(head);
Display(head);
}
答案 0 :(得分:0)
首先,typedef指针不是一个好主意。看看this thread可以得到更好的讨论。
要更改链接列表的标题,必须先通过引用将其传递,然后在函数内部对其进行更改。为了获得更好的可视化效果,我忽略了typedef。
// Notice that now you need to pass a pointer to a pointer, not just a pointer
void InsertFront(struct nodes **head)
{
int num;
struct nodes *temp = malloc(sizeof(node));
printf("Enter The Value Of Node\n");
scanf("%d", &num);
temp->data = num;
if (*head == NULL)
{
temp->next = NULL;
// by doing *head = temp we change the variable head declared in main
*head = temp;
}
else
{
temp->next = *head;
// Same thing here, we are updating the head by doing *head = ...
*head = temp;
}
}
当您要调用InsertFront
函数时:
struct nodes *head = NULL;
InsertFront(&head); // notice the &
答案 1 :(得分:0)
这是已修复错误的工作代码。
#include <stdio.h>
#include <stdlib.h>
struct nodes
{
int data;
struct nodes *next;
};
typedef struct nodes *node;
void InsertFront(node *head)
{
int num;
node temp = (node)malloc(sizeof(node));
printf("Enter The Value Of Node\n");
scanf("%d", &num);
temp->data = num;
if (*head == NULL)
{
temp->next = NULL;
*head = temp;
}
else
{
temp->next = *head;
*head = temp;
}
}
void Display(node head)
{
node q;
if (head == NULL)
{
printf("Linked List Seems To Be Empty");
}
else
{
q = head;
while (q != NULL)
{
printf("%d -> ", q->data);
q = q->next;
}
}
}
int main()
{
node head;
head = NULL;
InsertFront(&head);
Display(head);
}
您需要将main()的头部作为其地址传递(使用指向指针的指针)。在前一种情况下,磁头没有得到更新,由于这个原因,它表明列表为空。现在,输入的节点已正确显示在此代码中。