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
Posted: Tue Jul 12, 2022 8:21 am
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;}
#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;}