hello ,到今天我想将Insert At Front链接列表更改为Insert At Back链接列表,我不确定Insert In Back代码但Insert At Front代码没有错误。
问题列表是代码中的函数void insert_at_back(LN ** hptr,int d) 第二
如何从:C program to insert node at the end of Singly Linked List
这是Insert At Front链表代码(没有bug )
#include<stdio.h>
#include<stdlib.h>
struct listnode {
int data;
struct listnode *next;
};
typedef struct listnode LN;
void insert_at_front(LN **hptr, int d);
void print(LN *head);
int sum(LN *head);
int main(){
LN *head;
head = NULL;
int d;
printf("Enter data: ");
do{
scanf("%d", &d);
if(d > 0){
insert_at_front(&head,d);
}
}while(d > 0);
printf("=");
print(head);
printf("\n=%d", sum(head));
return 0;
}
void insert_at_front(LN **hptr, int d){
LN* newNode= (LN*)malloc(sizeof(LN));
newNode->data = d;
newNode->next= *hptr;
*hptr = newNode;
}
void print(LN *head){
while(head !=NULL){
printf("%d ",head->data);
head = head->next;
}
}
int sum(LN *head){
int temp=0;
while(head !=NULL){
temp+=head->data;
head = head->next;
}
return temp;
}
这是Insert At Back链接列表代码(它有问题或错误)
#include<stdio.h>
#include<stdlib.h>
struct listnode {
int data;
struct listnode *next;
};
typedef struct listnode LN;
void insert_at_back(LN **hptr, int d);
void print(LN *head);
int sum(LN *head);
int main(){
LN *head;
head = NULL;
int d;
printf("Enter data: ");
do{
scanf("%d", &d);
if(d > 0){
insert_at_back(&head,d);
}
}while(d > 0);
printf("=");
print(head);
printf("\n=%d", sum(head));
return 0;
}
void insert_at_back(LN **hptr, int d){
LN* head = *hptr;
LN* newNode = (LN*)malloc(sizeof(LN));
if(newNode==NULL){
printf("Unable to allocate memory\n");
}else{
newNode->data = d;
newNode->next= NULL;
while(head->data!= NULL){
head=head->next;
}
head->next=newNode;
}
}
void print(LN *head){
while(head !=NULL){
printf("%d ",head->data);
head = head->next;
}
}
int sum(LN *head){
int temp=0;
while(head !=NULL){
temp+=head->data;
head = head->next;
}
return temp;
}
感谢您的回答,如果您不理解,我很抱歉。
我是新手
IHM
答案 0 :(得分:0)
insert_at_back()
功能中存在一些问题。
第一个问题:
while(head->data!= NULL){
这应该是:
while(head->next!= NULL){
第二个问题:
未在head
函数中检查NULL
指针insert_at_back()
。
第三个问题:
未初始化hptr
函数中的insert_at_back()
。
您的insert_at_back()
应该是:
void insert_at_back(LN **hptr, int d){
LN* head = *hptr;
LN* newNode = malloc(sizeof(LN));
if(newNode==NULL){
printf("Unable to allocate memory\n");
}else{
newNode->data = d;
newNode->next= NULL;
if (head != NULL) {
while(head->next!= NULL){
head=head->next;
}
head->next=newNode;
}
else
*hptr = newNode;
}
}
最后但并非最不重要 - do not typecast malloc result。