有人可以检查插入结束功能发生了什么. 它没有创建主函数中提到的所有块



我在插入和惰性前端函数的 if else 循环中添加了 print 语句,这导致每次我从 main 调用这两个函数时都打印 printf 语句......但在显示中,它不会显示所有值。我想也许节点在调用时在某处损坏了......请参阅代码下方的输出。它只显示三个值,而它应该显示我在 main(( 中输入的所有值。 这是我的代码。

#include <stdio.h>
#include <stdlib.h>
struct node
{
int value;
struct node* ptr;
};
struct node* insertatend(struct node* h, int value)
{
struct node* newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->value = value;
newnode->ptr = NULL;
if (h == NULL)
return newnode;
else {
while(h->ptr!=NULL)
h=h->ptr;
h->ptr = newnode;
return h;
}
}
struct node* insertatfront(struct node* h, int value)
{
struct node* newnode;
newnode = (struct node*)malloc(sizeof(struct node));
if (h == NULL) {
newnode->value = value;
newnode->ptr = NULL;
return newnode;
}
else
{
newnode->value = value;
newnode->ptr = h;
return newnode;
}
}
void display(struct node* h)
{
while ((h->ptr) != NULL)
{
printf("The value stored in the block is %dn", h->value);
h = h->ptr;
}
if (h->ptr == NULL)
printf("The value stored in the block is %dn", h->value);
}
void main()
{
struct node* head;
head = (struct node*)malloc(sizeof(struct node));
head = insertatend(head, 90);
head = insertatend(head, 30);
head = insertatfront(head, 5);
head = insertatend(head, 12);
head = insertatend(head, 1);
head = insertatfront(head, 25);
display(head);
}
/* Output:The value stored in block is 25
* The value stored in block is 5
* The value stored in block is 1
*/

你在代码中似乎犯的主要错误:

1( 在插入函数中修改head指针。这句话在insertatend

while(h->ptr!=NULL)
h=h->ptr;

更改列表本身的头部。相反,您应该使用不同的指针来遍历到最后。 将insertatend更改为:

struct node* insertatend(struct node* h, int value)
{
struct node* newnode;
newnode = (struct node*)malloc(sizeof(struct node));
newnode->value = value;
newnode->ptr = NULL;
if (h == NULL){
h=newnode;
}
else {
struct node *temp;
temp=h;
while(temp->ptr!=NULL) temp=temp->ptr;
temp->ptr = newnode;
}
return h;
}

2(h为空的情况永远不会发生,因为您已经在main中错误地定位了head。从main中删除语句head = (struct node*)malloc(sizeof(struct node));

相关内容

  • 没有找到相关文章

最新更新