0

I am trying to insert an element at second last place of my linked list...Please help me out I have created a function to enumerate the linked list with values 1,2,3...etc Then I have a function to insert at second last, and then I have a function to display the list.

#include <stdio.h>
#include<stdlib.h>
struct node{
    int data;
    struct node *next;
}*head=NULL;
void insert(int x){
 int i = 1;
 struct node *temp,*temp2=head;
 while(x>0){
     x--;
     temp = (struct node*)malloc(sizeof(struct node));
     head->data=i++;
     head->next=temp;
     head=temp;
     }
     head->next=NULL;
head=temp2;
}

void insertSecondLast(int x){
struct node *prev,*insert,*temp=head;
insert = (struct node*)malloc(sizeof(struct node));
insert->data=x;
while(head->next!=NULL){
    prev = head;
    head=head->next;
    }
prev->next=insert;
insert->next=head;
head=temp;
}

void display(){
    printf("\n[");
    while(head->next!=NULL){
        printf("%d, ",head->data);
        head=head->next;
    }
    printf("NULL]");
}


int main(void) {

     insert(4);
     insertSecondLast(100);
     display();
     return 0;
}
6
  • 2
    Use a debugger. But look at your insert function. You are dereferencing head before ever setting it. Commented Jul 15, 2018 at 5:12
  • e.g. What is the address held by head the first time you encounter head->data=i++;? Commented Jul 15, 2018 at 5:30
  • Read absolutely how to debug small programs Commented Jul 15, 2018 at 5:31
  • Also display functions should be while(head) { printf("%d, ", head->data); head = head->next; } Commented Jul 15, 2018 at 5:39
  • Thanks @David C. Rankin ... I allocated the memory now it runs. Commented Jul 15, 2018 at 5:41

1 Answer 1

1

In your insert function, you are de-referencing the NULL pointer (head is set to NULL initially). The OS does not allow you to de-reference the NULL address, so you get a seg fault at run-time.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot... I allocated memory for head in the main function. Now it runs. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.