I have to create functions that add elements to the beginning and end of a linked list using C. When I try to run what I

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

I have to create functions that add elements to the beginning and end of a linked list using C. When I try to run what I

Post by answerhappygod »

I have to create functions that add elements to the beginningand end of a linked list using C. When I try to run what I'vewritten, I get a segmentation fault. What am I doing wrong?
#include <stdio.h>#include <stdlib.h>
struct node{ int data; struct node *next;};typedef struct node node;
node* insertFront(node* head, int d){ node *tmp = NULL; tmp = malloc(sizeof(node));
tmp->data = d;
tmp->next = head;
head = tmp;}
node* insertBack(node* head, int d){ node* tmp = malloc(sizeof(node));
node *last = head;
tmp->data = d;
tmp->next = NULL;
if (head == NULL) { head = tmp; exit; }
while (last->next != NULL) last = last->next;
last->next = tmp; exit;}
void print(node* head){ while (head != NULL) { printf(" %d ",head->data); head = head->next; } printf("\n");}
int main(){ node* head = NULL;
insertBack(head, 5);
insertFront(head, 4);
insertFront(head, 3);
insertBack(head, 6); insertBack(head, 7);
print(head);
return 0;}
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply