I have created a function called 'Insert' for inserting a new node in a Linked List. It takes the value and the head node for insertion. When I manually add the nodes myself, the program runs as expected however I get a segmentation fault when I use the function for adding a node.
I am able to make the function work with a couple of little tweaks but there's another catch, I lose the head node's property of just being a pointer, it now contains some garbage data in it which gets printed when I print the LinkedList.
The tweak I perform is:
Change Line 26 to: A->next = NULL;
Change Line 17 to: while(temp->next != NULL)
The 'segmentation fault' occurs at Line 20 (when the tweak is not done):
Line 20 -----> temp->next = addTo;
I've already tried passing the arguments by reference, using global variables for the head node and checking the logic of the function. The logic works for manually adding a node.
I have attached the complete code below:
#include <bits/stdc++.h>
using namespace std;
struct ListNode {
int data;
ListNode *next;
};
void Insert(int x , ListNode* head)
{
ListNode* addTo = new ListNode();
addTo->data = x;
addTo->next = NULL;
ListNode* temp;
temp = head;
while(temp != NULL)
temp = temp->next;
temp->next = addTo;
}
int main()
{
ListNode* A;
A = NULL;
//Inserting A Node Manually
// ListNode* first = new ListNode();
// first->data = 9;
// first->next = NULL;
// while(A != NULL)
// A = A->next;
// A = first;
//Inserting using Insert function.
Insert(2,A);Insert(3,A);Insert(6,A);Insert(7,A);
//Printing
ListNode* temp = A;
while(temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
return 0;
}
I expected the node to be added to the list as the logic seems to be correct, however I am getting a segmentation fault.
Any help/insight into this would help a lot.
Thank You.