I was trying to implement sorting by following method in C - Accept integers and save them into array. Pass each array value and arrange it in a doubly linked list in an ascending order. I have written the program but I am facing a crash, debugging says its a segmentation fault in display function, however I still haven't been able to make that out. Hints would be appreciated.
#include<stdio.h>
#include<stdlib.h>
struct node //Doubly linked list to store in ascending order
{
int info;
struct node *llink; //Left link
struct node *rlink; //Right link
};
typedef struct node *NODE; //Define a custom data type for pointer to node(a structure)
/*Accept an integer argument and insert into a doubly linked list at appropriate position to arrange in ascending order*/
void list_sort(NODE head,int item)
{
NODE cur,prev,temp,prev_to_prev;
temp=malloc(sizeof(struct node)); //Allocate block of memory for a new node to be inserted
temp->info=item; //Assign the integer to info field of the node
if(head->rlink==NULL) //head->rlink==NULL when the first node is being inserted
{
head->rlink=temp;
temp->llink=head;
temp->rlink=head; //Last points to first because of circular representation used here
return;
}
cur=head->rlink;
while(cur!=head)
{
prev=cur->llink;
if(temp->info<cur->info&&temp->info>=prev->info) //when prev->info<temp->info<cur->info insert between prev and cur
{
prev->rlink=temp;
temp->llink=prev;
cur->llink=temp;
temp->rlink=cur;
return;
}
else if(temp->info>=cur->info && temp->info>prev->info) // when temp->info>cur->info and also > prev->info insert at last
{
cur->rlink=temp;
temp->llink=cur;
return;
}
else if(temp->info<cur->info && temp->info<prev->info) // when temp->info<cur->info and also < prev->info insert before them
{
prev_to_prev = prev->llink;
prev_to_prev->rlink=temp;
temp->rlink=prev;
return;
}
cur=cur->rlink;
}
}
void list_disp(NODE head)
{
NODE cur;
printf("\nSorted elements are - \n");
cur=head->rlink;
while(cur!=head)
{
printf("%d\n",cur->info);
cur=cur->rlink;
}
}
void main()
{
int items[10],i;
NODE head,cur;
head=malloc(sizeof(struct node));
head->llink=head->rlink=NULL;
head->info=0;
printf("Enter 5 items to sort: \n"); //Take only 5 items for now
for(i=0;i<5;i++)
scanf("%d",&items[i]); //Read 5 items
for(i=0;i<5;i++)
list_sort(head,items[i]); //Call function for all 5 items
list_disp(head); //Display the linked list entry by entry
}
headinmain()be always unmodified if you don't pass by reference?