lkal
lkal

Reputation: 25

inserting a node at the front of a linked list

#include <stdio.h>
#include <stdlib.h>
#include "list.h"

void listInsertHead (List l, int val) {
    Node start;
    start = calloc(1, sizeof(node));
    start->value = val;
    start->next = l->head;
    l->head = start;

    Node current;
    while (current != NULL) {
        printf("data is %d\n", current->value);
        current = current->next;
    }
}

 int main(int argc, char *argv[]) {

    List new = calloc(1, sizeof(list));
    Node first = calloc(1, sizeof(node));
    Node second = calloc(1, sizeof(node));
    Node third = calloc(1, sizeof(node));

    first->value = 10;
    new->head = first;
    second->value = 20;
    third->value = 30;

    first->next = second;
    second->next= third;
    third->next = NULL;

    listInsertHead(new, 5);

    return 0;
}


typedef struct _node *Node;    
typedef struct _list *List;    

typedef struct _list {
    Node head; 
} list;

typedef struct _node {
    int value;
    Node next;  
} node;

I'm trying to add a new node to the beginning of the linked list as the head. However, I keep getting segmentation fault so I'm unsure what to do. The structs are at the bottom of the code. So what I'm attempting to do is:

1->2->3->NULL

new(node)->1->2->3->NULL

Upvotes: 0

Views: 151

Answers (1)

Virtually Nick
Virtually Nick

Reputation: 368

Your segfault comes from trying to print the list without initializing the current variable:

Node current;
while (current != NULL) {
    printf("data is %d\n", current->value);
    current = current->next;
}

You haven't set it to anything, but are trying to loop through it - you need to initialize it:

Node current = l->head;

Upvotes: 3

Related Questions