Appending Linked List in C seg fault errors - c

I am having some trouble adding integers to the end of my linked list. I am very new to C and had part of my program working properly (the push function). I want to return a pointer to a struct node, and I am not quite sure where I am going wrong in my append function.
~Thanks.
enter code here
//node.h
#ifndef NODE_H
#define NODE_H
struct node{
int val;
struct node *next;
};
int length(struct node *);
struct node* push(struct node *, int); //adds integer to front of list.
struct node* append(struct node *, int); //adds integer to back of list.
void print(struct node *, int);
#endif
//node.c
#include "./node.h"
#include<stdlib.h>
#include<stdio.h>
int length(struct node *current){
if(current->next != NULL)
return 1 + length(current->next);
else
return 1;
}
struct node* push(struct node *head, int num){
struct node *temp = malloc(sizeof(struct node));
temp->val = num;
temp->next = head;
head = temp;
temp = NULL;
return head;
}
struct node* append(struct node *current, int num){
if(current != NULL){
append(current->next, num);
}
else{
struct node* temp = malloc(sizeof(struct node));
temp->val = num;
temp->next = NULL;
current = temp;
return current;
}
}
void print(struct node* head, int size){
printf("The list is %i", size);
printf(" long \n");
struct node* temp;
temp = head;
while(temp != NULL){
printf("%d", temp->val);
printf(" ");
temp = temp->next;
}
printf(" \n");
}
//Main
#include "./node.h"
#include<stdlib.h>
#include<stdio.h>
int main(){
char ans[2];
int num;
struct node* head = NULL;
do{
printf("Enter a integer for linked list: ");
scanf("%d", &num);
head = append(head, num);
printf("Add another integer to linked list? (y or n) ");
scanf("%1s", ans);
}while(*ans == 'y');
print(head, length(head));
return 0;
}

I think what is missing is that the recursive part of the function needs to set current->next. This has the effect of setting every node's next pointer to what it was until you get to the end of the list, when it is set to the newly malloced node.
struct node* append(struct node *current, int num){
if(current != NULL){
current->next = append(current->next, num);
return current;
}
else {
struct node* temp = malloc(sizeof(struct node));
if (temp == NULL) abort();
temp->val = num;
temp->next = NULL;
return temp;
}
}

Related

Error: in creation of Linked List Display function

I am trying to create a linked list with display() function in it but i continuously getting error in it. a function not able to display element in output.
I have try various online solution of code but not worked on my code.
Below is my code if anyone have any idea. let me tell to solve it
#include <stdio.h>
#include <stdlib.h>
struct node{
int data;
struct node *next;
};
int create(int n){
int d1,d2,i;
struct node *head, *temp, *newnode;
head = (struct node *) malloc(sizeof(struct node));
printf("enter the data for node 1");
scanf("%d",&d1);
head->data = d1;
head->next = NULL;
temp = head;
for(i=2; i<=n; i++){
newnode = (struct node *)malloc(sizeof(struct node));
printf("enter a data for %d node",i);
scanf("%d",&d2);
newnode->data = d2;
newnode->next = NULL;
temp->next = newnode;
temp = temp->next; // newnode can also use instead of temp->next
}
void printList(struct node* node) {
while (node != NULL) {
printf(" %d ", node->data);
node = node->next;
}
}
}
int main()
{
struct node* head = NULL;
int n;
printf("Enter number of node to create");
scanf("%d",&n);
create(n);
printList(head);
return 0;
}
Change return type of the create function to return the address of the node like this: struct node * create(int n) and change return value to: return head;.
Finally, in main() save the returned address in head pointer: head = create(n);

change Insert At Front linked list to Insert At Back linked list in C Language

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
There are few of problems in your insert_at_back() function.
First problem:
while(head->data!= NULL){
This should be :
while(head->next!= NULL){
Second problem:
Not checking for head pointer NULL in insert_at_back() function.
Third problem:
Not initializing the hptr in insert_at_back() function.
Your insert_at_back() should be:
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;
}
}
Last but not least - do not typecast malloc result.

Linked list in C seg faults

Having seg fault erros with my code posted below. I am new to C and have been having some trouble with it. Basically in my main I made a struct node* head (pointer to a struct node) and assigned it to NULL. I then send the struct node * head to the push function that should insert user defined integers into the front of the list. I believe I am having issues inside the push function, any help would be very aprecciated.
~Thanks
//node.h
struct node{
int val;
struct node* next;
};
int length(struct node *);
struct node* push(struct node *, int);
void print(struct node *, int);
//node.c
#include "./node.h"
#include<stdlib.h>
#include<stdio.h>
int length(struct node *current){
if(current->next != NULL)
return 1 + length(current->next);
else
return 1;
}
struct node* push(struct node *head, int num){
struct node *temp = malloc(sizeof(struct node));
temp->val = num;
temp->next = head;
head = temp;
return head;
}
void print(struct node* head, int size){
printf("The list is %i", size);
printf(" long \n");
struct node* temp;
temp = head;
while(temp != NULL){
printf("%d", temp->val);
printf(" ");
temp = temp->next;
}
printf(" \n");
}
//main program
#include "./node.h"
#include<stdlib.h>
#include<stdio.h>
int main(){
char ans;
int num;
struct node* head = NULL;
do{
printf("Enter a integer for linked list: ");
scanf("%d", &num);
head = push(head, num);
printf("Add another integer to linked list? (y or n) ");
scanf("%1s", &ans);
}while(ans == 'y');
print(head, length(head));
return 0;
}
scanf will read n+1 characters into the provided buffer when you use %ns because of the null terminator.
Use a buffer of size 2 (char ans[2];) and check the first character (ans[0] == 'y'). You will also no longer need to take the address of ans when calling scanf).

Linked lists, how to insert if head does not exist?

I got a linked list, which should save the Outcome (W or L) and the gained/lost points for each match. All good so far, but I'm getting trouble when the head does not exist/is empty. I also realized I have a pretty bad overview of how to implement linked lists, anyone got good and understandable resources? Anyway this is my code:
#include <stdio.h>
#include <stdlib.h>
struct node {
int point;
char outcome;
struct node *next;
};
void add(struct node *data){
if(data == NULL){
data = malloc(sizeof(struct node));
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
data->point=point;
data->outcome=outcome;
data->next=NULL;
}else{
struct node *current= data;
while(current->next != NULL){
current = current->next;
}
current->next = malloc(sizeof(struct node));
current=current->next;
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
current->point=point;
current->outcome=outcome;
current->next=NULL;
}
}
void print(struct node *data){
struct node *current = data;
while(current != NULL){
printf("%c with %3d\n",current->outcome,current->point);
current = current->next;
}
}
int main()
{
struct node *head=NULL;
add(head);
add(head);
add(head);
print(head);
}
Any help would be appreciated :)
When you execute:
void add(struct node *data){
if(data == NULL){
data = malloc(sizeof(struct node));
the value of head does not change in the calling function.
Suggest a change of strategy.
struct node* add(struct node *head)
{
if(head == NULL){
head = malloc(sizeof(struct node));
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
head->point=point;
head->outcome=outcome;
head->next=NULL;
}else{
struct node *current= head;
while(current->next != NULL){
current = current->next;
}
current->next = malloc(sizeof(struct node));
current=current->next;
printf("Outcome and points?\n");
int point;
char outcome;
scanf("%c %d",&outcome,&point);
fgetc(stdin);
current->point=point;
current->outcome=outcome;
current->next=NULL;
}
return head;
}
And, then change the usage:
int main()
{
struct node *head = add(NULL);
add(head);
add(head);
print(head);
}
You can simplify the code by starting the list with an anchor node. An anchor node is a node that is only used for its next pointer. In the code below, the call to calloc creates the anchor node, and sets all of the fields in the anchor to 0. In other words, a node is created with next == NULL.
Note that when printing the list, the for loop starts by skipping the anchor node with for (list = list->next;...)
#include <stdio.h>
#include <stdlib.h>
struct node
{
int point;
char outcome;
struct node *next;
};
void add( struct node *list )
{
struct node *data;
data = malloc(sizeof(struct node));
data->next = NULL;
printf("Outcome and points?\n");
scanf("%c %d",&data->outcome,&data->point);
fgetc(stdin);
while (list->next != NULL)
list = list->next;
list->next = data;
}
void print( struct node *list )
{
for (list = list->next; list != NULL; list = list->next)
printf("%c with %3d\n", list->outcome, list->point);
}
int main()
{
struct node *head = calloc( 1, sizeof(struct node) );
add(head);
add(head);
add(head);
print(head);
}
Side note: I've omitted some error checking to keep things simple, you should really be checking the return values from calloc, malloc, and scanf and handle any errors. And, of course, you should free all of the nodes at the end.

What's with the program why is it not printing any result?

struct node{
int data; struct node *next;
};
void push(struct node* head, struct node* n){
if(n!= NULL){
if(head==NULL)
head = n;
else {
n->next = head;
head = n;
}
} else printf("Cannot insert a NULL node");
}
struct node* pop(struct node* head){
if(head!=NULL){
struct node *n = head;
head = head->next;
return n;
} else {
printf("The stack is empty");
return NULL;
}
}
int main(){
int i;
struct node *head = NULL, *n;
for(i=15;i>0;i--){
struct node *temp = malloc(sizeof(struct node));
temp -> data = i;
temp->next = NULL;
push(head,temp);
}
n = head;
while(n!=NULL){
printf("%d ",n->data);
n=n->next;
}
return 0;
}
You need to pass the address of the pointer head to the function push. I your case the head is not getting modified because you are only passing the value in the head.
void push(struct node** head, struct node* n){
if(n!= NULL){
if(*head==NULL)
*head = n;
else {
n->next = *head;
*head = n;
}
} else printf("Cannot insert a NULL node");}
int main(){
int i;
struct node *head = NULL, *n;
for(i=15;i>0;i--){
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp -> data = i;
temp->next = NULL;
push(&head,temp);
}
n = head;
while(n!=NULL){
printf("%d ",n->data);
n=n->next;
}
return 0;}
You are passing the head pointer by value to the function push(head,temp);. The changes to head done inside push will not be reflected in the main() function.
You should pass address of head to push().
push(&head, temp);
and inside push():
*head = n;
Similar change will be required for pop(). You can verify what I am saying by adding a printf inside the loop in main() as: printf("%p\n", head);. The value of head will remain unchanged.
BTW, it is good practice to add a \n at the end of statement inside printf, it flushes the stdout stream immmediately hence your output is printed immediately on stdout (your computer screen).

Resources