如何解决链表中显示节点的代码不起作用
我在链表中编写了插入代码。但是当我运行此代码时,我的显示功能无法正常工作并打印其他内容。
**ERROR IN CODE**
这里,我将 head 函数声明为全局变量并将其设置为 NULL。之后,当我返回主函数并完成它时。在一些代码将一个节点分配给结构 p 并且第一个节点被声明为 head (现在我们的 head 不是 NULL,它包含节点中的一些值),然后我们调用 display 函数。 现在,当我们返回 display 函数并运行它时,它显示我们的 head 是 NULL 并且不是 NULL。
下面是我的代码
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
struct node* head = NULL,* tail = NULL;
void printList()
{
struct node* ptr = head;
if (head == NULL)
{
printf("Empty list\n");
}
printf("Nodes of the list are: \n");
while (ptr != NULL)
{
printf("%d \t",ptr->data);
ptr = ptr->next;
}
printf("\n");
}
struct node* insertion(struct node** head,struct node** tail,int ele,int pos)
{
int i;
struct node* new_node,* temp;
new_node = (struct node*)malloc(sizeof(struct node));
if (new_node == NULL)
{
printf(" Dynamic memory allocation Failed. Insertion can not be done");
return NULL;
}
else
{
new_node->data = ele;
if (pos < 1)
{
printf(" Inappropriate position");
return NULL;
}
else if (*head == NULL)
{
new_node->next = NULL;
*head = *tail = new_node;
return (new_node);
}
else if (pos == 1)
{
new_node->next = *head;
*head = new_node;
return(new_node);
}
else
{
temp = *head;
i = 1;
while (i < pos - 1 && temp != NULL)
{
temp = temp->next;
i++;
}
if ((temp == NULL) || ((i == pos - 1) && (temp->next == NULL)))
{
new_node->next = NULL;
(*tail)->next = new_node;
(*tail) = new_node;
return (new_node);
}
else
{
new_node->next = temp->next;
temp->next = new_node;
return (new_node);
}
}
}
}
int main()
{
struct node* head,* tail,* p;
int n,i,ele,pos;
do {
printf(" Enter the number of elements initially in linked list: ");
scanf("%d",&n);
if (n < 0)
{
printf(" Enter the number greater than zero \n");
}
} while (n < 0);
printf(" Enter the elements of linked list \n");
for (i = 0; i < n; i++)
{
p = (struct node*)malloc(sizeof(struct node));
printf("%d element : ",i + 1);
scanf("%d",&p->data);
if (head == NULL)
{
head = p;
tail = p;
}
else
{
tail->next = p;
tail = p;
}
}
printList();
printf(" Enter the value which you want to insert: ");
scanf("%d",&ele);
printf(" Enter the position at which you want to insert: ");
scanf("%d",&pos);
insertion(&head,&tail,pos);
return 0;
}
解决方法
int main()
{
struct node* head,* tail,* p;
这是你的问题。您在名为 head
和 tail
的 main 中声明局部变量,它们在该范围内隐藏全局变量。当您稍后在 main 中分配 head 和 tail 时,您正在更改 locals 的值。全局变量保持不变。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。