I have written a Code for Implementing Singly Linked List in C. While my code does compile, I get a segmentation fault when attempting to run my code.
The Code is:
#include <stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head;
void InsertAtPosition(int data, int n){
int i;
struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node*));
temp1->data = data;
temp1->next = NULL;
if(n == 1){
temp1->next = head;
head = temp1;
return;
}
struct Node* temp2 = head;
for(i=0; i<n-2; i++){
temp2 = temp2->next;
}
temp1->next = temp2->next;
temp2->next = temp1;
}
void Print(){
struct Node* temp = head;
printf("List is: \n");
while(temp != NULL){
printf("\t%d\n", temp->data);
temp = temp->next;
}
}
int main(){
head = NULL;
InsertAtPosition(10, 1);
InsertAtPosition(11, 2);
InsertAtPosition(12, 3);
Print();
return 0;
}
The code is giving an Error Segmentation fault (core dumped)
.
What exactly am I doing Wrong?