I tried to create a linked list with 4 nodes and then added a node using the Insert() fucntion. The overall program has the following framework.
struct Node: Defining the structure of each node of my linked list.Node_s* Initialize(): This is just to initialize an empty node and return a pointer to the rest of the list; this is made just to satisfy the requirement of the program.int Insert(): This function inserts a node such that the sorting of the list is maintained!main(): I am executing the program here in main, by calling the functionsInitialize()andInsert()
I think there is some problem in the way the insert() function is interacting with the main function. The changes I am making in the insert() function are not showing up in the main function. Can someone help me figure out why this is happening?
Code:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
} Node_s;
Node_s* Initialize(){
Node_s init_node;
Node_s* headlist;
init_node.data = 0;
headlist = init_node.next ;
return headlist;
}
int Insert(Node_s* listhead, int data){
Node_s* ptr = listhead;
if(data>0){
while((data > ptr->data)&&(ptr->next!=NULL)){
ptr = ptr->next;
}
Node_s a;
a.data = data;
if(ptr->next==NULL){
a.next = NULL;
}
else{
a.next = ptr->next;
}
ptr->next = &a;
int count =0;
Node_s* potr = listhead;
printf("\ninside the function\n ");
while( potr!= NULL)
{
printf("count %d %d \n" , count, potr->data);
count = count +1;
potr = potr->next;
}
return 0;
}
else{
printf("enter valid positive integer");
return 1;
}
}
int main()
{
// 1st Node
Node_s two;
Node_s* ptr = Initialize();
ptr = &two;
// 2nd Node
two.data = 1;
Node_s three;
two.next = &three;
// 3rd Node
three.data = 2;
Node_s four;
three.next = &four;
// 4th Node
four.data = 3;
four.next = NULL ;
Insert(ptr, 5);
printf("\n outside the function\n");
int count =0;
Node_s* potr = ptr;
while( potr!= NULL)
{
printf("count %d %d \n" , count, potr->data);
count = count +1;
potr = potr->next;
}
return 0;
}
Output message
inside the function
count 0 1
count 1 2
count 2 3
count 3 5
outside the function
count 0 1
count 1 2
count 2 3
count 3 82624112
count 4 84386816
count 5 0
count 6 -17958193
zsh: segmentation fault
"/Users/as/Desktop/A2/"tempCodeRunnerFile