如何解决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);
}
输出如下所示: enter image description here
解决方法
在这个循环之后
while (temp!=NULL)
{
temp = temp->next;
}
指针temp
等于NULL
。所以这个空指针在这个语句中是用来访问内存的
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。