我有一个 C 程序可以在链表的开头插入元素,但是当我尝试打印元素时,它总是跳过第一个元素。有人可以指出我在我的程序中做错了什么吗。
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
void PrintElements();
void InsertElement(int x);
struct node
{
int data;
struct node* next;
};
struct node* HEAD;
struct node* temp;
struct node* temp1;
void PrintElements()
{
temp1=HEAD;
while(temp1->next!=NULL)
{
printf("\n\r Data %d\n\r",temp1->data);
printf("\n\r Address %x\n\r",temp1->next);
temp1=temp1->next;
}
}
void InsertElement(int x)
{
struct node* temp=(struct node*)malloc(sizeof(struct node));
temp->data=x;
temp->next=HEAD;
HEAD=temp;
}
int main()
{
int i, x;
int n; //n stores the number of elements to be added to the linked list
HEAD=NULL; //Assigning HEAD to null when there are no elements in the list
printf("Enter the number of elements\n");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\n\rEnter the number");
scanf("%d",&x);
InsertElement(x);
PrintElements();
}
return 0;
}
当我更改以下行时
while(temp1->next!=NULL)
到
while(temp1!=NULL)
程序运行正常,但我仍然不明白为什么。
最佳答案
while(temp1->next!=NULL)
将此更改为
while(temp1 != NULL)
它应该可以正常工作。
原因:我认为它不会打印您输入的第一个元素。
示例:输入:1 2 3
链表形式为:3 -> 2 -> 1 -> NULL
使用的符号:每个数字都是数据
,箭头表示指针next
。
然后当你开始循环时,对于每次迭代:
temp1
指向3
的地址
temp1 -> next != NULL
(当temp1 -> next
指向2
的地址时为真)打印
的地址3
和temp1
现在指向2
temp1 -> next != NULL
(当temp1 -> next
指向1
的地址时为真)打印
的地址2
和temp1
现在指向1
temp1 -> next != NULL
这变为 False 因为temp1
指向1
的地址> 和temp1 -> next
为 NULL。
所以我们永远不会进入循环以打印 1
。
所以正确的做法是使用 temp1 != NULL
因为这将消除上述错误。
关于c - 链表遍历跳过第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41404995/