C中在单链表末尾添加节点的函数不起作用



我刚刚在C中编写了一个函数,该函数应该在链表的末尾添加一个节点,但当我编译该程序时,我在控制台中一无所获。以下是函数的主体:

void addAtend(node *head, int val){
node *temp;
node *tempVal;
temp =head;
tempVal= (node*)malloc(sizeof(node));
if(tempVal==NULL){
printf("Error! Memory was not allocated!");
exit(-1);
}
tempVal ->data=val;
tempVal->next=NULL;
while (temp!=NULL)
{
temp = temp->next;
}
temp->next = tempVal;

}

这是完整的C程序:

#include <stdlib.h>
#include <stdio.h>
typedef struct linked {
int data;
struct linked *next;

} node;
//function to ietrate through a linked list
void printer(node *head){
node *temp = head;
while (temp!=NULL)
{
printf("%d ", temp->data);
temp = temp->next;
}

}
//function to add a value to the end of the linked list
void addAtend(node *head, int val){
node *temp;
node *tempVal;
temp =head;
tempVal= (node*)malloc(sizeof(node));
if(tempVal==NULL){
printf("Error! Memory was not allocated!");
exit(-1);
}
tempVal ->data=val;
tempVal->next=NULL;
while (temp!=NULL)
{
temp = temp->next;
}
temp->next = tempVal;


}
int main(){
node *ptr = (node*)malloc(sizeof(node));
if(ptr==NULL){
printf("Error!");
exit(-1);
}
node *head;
head = ptr;

ptr->data = 30;
ptr->next = (node*)malloc(sizeof(node));
ptr->next->data =50;
ptr->next->next = NULL;

addAtend(head, 40);
printer(head);
}

输出如下:在此处输入图像描述

有人能看看这段代码,告诉我函数出了什么问题吗?

循环之后

while (temp!=NULL)
{
temp = temp->next;
}

指针CCD_ 1等于CCD_。所以这个空指针被用来访问这个语句中的内存

temp->next = tempVal;

从而导致未定义的行为。

该功能可以通过以下方式定义

int addAtend( node **head, int val )
{
node *new_node = malloc( sizeof( node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = val;
new_node->next = NULL;
while ( *head != NULL ) head = &( *head )->next;
*head = new_node;
}
return success;
}

该函数可以像一样调用

addAtend( &head, 40 );

这是一个示范节目。

#include <stdio.h>
#include <stdlib.h>
typedef struct linked {
int data;
struct linked *next;
} node;
int addAtend( node **head, int val )
{
node *new_node = malloc( sizeof( node ) );
int success = new_node != NULL;
if ( success )
{
new_node->data = val;
new_node->next = NULL;
while ( *head != NULL ) head = &( *head )->next;
*head = new_node;
}
return success;
}
FILE * printer( const node *head, FILE *fp )
{
for ( ; head != NULL; head = head->next )
{
fprintf( fp, "%d -> ", head->data );
}

fputs( "null", fp );

return fp;
}
int main(void) 
{
node *head = NULL;

addAtend( &head, 30 );
addAtend( &head, 40 );
addAtend( &head, 50 );

fputc( 'n', printer( head, stdout ) );
return 0;
}

程序输出为

30 -> 40 -> 50 -> null

相关内容

  • 没有找到相关文章

最新更新