hello , to day i'm want to change Insert At Front linked list to Insert At Back linked list,i'm not sure Insert At Back code but Insert At Front code not have bug .
problem list is function void insert_at_back(LN **hptr, int d) in code second.
how to from : C program to insert node at the end of Singly Linked List
this is Insert At Front linked list code (NOT have 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;
}
This is Insert At Back linked list code (it have problem or bug)
#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;
}
Thank you for answer ,i'm sorry if u not understand.
i'm newbie
ihm