我有一个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)
该程序可以正常运行,但我仍然无法理解原因。
您可以通过将PrintElements()
函数中的控制表达式更改为来解决您描述的问题temp1 != NULL
。这样,如果temp1
指向节点,则将打印data
和next
字段,并且循环将继续进行,直到没有更多节点为止。当遍历一个链表时,当您查看下一个节点来决定要对当前节点执行的操作时,通常看起来会感到困惑。但是此代码还有其他问题。
首先,最好将struct
指针声明为inmain()
并将其传递给函数,而不是将它们声明为全局变量。您应尽可能检查所调用函数的返回值。您应该检查scanf()
以确保输入符合预期;这也提供了一种控制输入循环的方法,从而无需用户在输入数据之前显式输入一个计数。您还应该检查调用返回的值malloc()
以捕获分配错误。temp
在下一行中取消引用时,代码中的这种分配错误将导致未定义的行为。
您应该free
分配所有内存,free()
每次调用一次malloc()
。当您next
在函数的列表中打印节点的地址时PrintElements()
,您将调用未定义的行为。要打印指针的值,应使用%p
格式说明符,并且必须将指针强制转换为(void *)
。最后,没有必要#include <malloc.h>
;stdlib.h
照顾您的需求。
这是实现建议的更改的代码的修改后的版本。请注意,在分配错误的情况下,消息将打印到stderr
,程序将被打印exit
。对的调用malloc()
已得到简化:没有理由malloc()
在C中强制转换结果,最好使用您要为其分配内存的指针的名称,而不是在给定的参数中使用显式类型malloc()
。将new_node
返回到调用函数,在该函数中,指向head
列表的指针被重新分配为指向new_node
。
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node* next;
};
void print_elements(struct node *start);
struct node * insert_element(int x, struct node *head);
int main(void)
{
struct node* head = NULL;
struct node* curr = NULL;
int x;
/* Read data into linked list */
printf("Enter the first integer (q to quit): ");
while (scanf("%d", &x) == 1) {
head = insert_element(x, head);
print_elements(head);
printf("Enter another integer (q to quit): ");
}
/* Free allocated memory */
while (head) {
curr = head;
head = curr->next;
free(curr);
}
return 0;
}
void print_elements(struct node *curr)
{
while(curr) {
printf(" Data: %d\n",curr->data);
printf("Address: %p\n\n",(void *) curr->next);
curr = curr->next;
}
}
struct node * insert_element(int x, struct node *head)
{
struct node *new_node = malloc(sizeof(*new_node));
if (new_node == NULL) {
fprintf(stderr, "Allocation error in function insert_element()\n");
exit(EXIT_FAILURE);
}
new_node->data = x;
new_node->next = head;
return new_node;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句