Search code examples
csegmentation-faultcircular-list

Display function of Circular Linked List Debugging


I have tried to implement Circular Linked List with features like insertion, deletion at position, then repeated insertion or deletion based on changing position. However there is a case when initially the list is not yet created and I want to insert at position 1. My program should allow this and should give invalid position for other positions for the mentioned case. However whenever I am trying to do this it is giving me segmentation fault during display in the while loop. Please help. My code is :

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

struct node
{
    int data;
    struct node *next;
};

typedef struct node node;

node *head;
int count=0;



void insert(int d,int pos)
{
    if((pos==(count+1))||(head==NULL))
    {
        addnode(d);
    }
    else
    {
        if(pos==1)
        {
            node *newnode = (node *)malloc(sizeof(node));
            newnode->data = d;
            newnode->next = head;
            head = newnode;
            tail->next = newnode;
        }
        else
        {
            int a = 1;
            node *temp = head;
            while(a!=(pos-1))
            {
                temp = temp->next;
                a++;
            }
            node *newnode = (node *)malloc(sizeof(node));
            newnode->data = d;
            newnode->next = temp->next;
            temp->next = newnode;
        }
        count++;
    }
}

void display()
{
    node *temp = head;
    if(head==NULL)
    {
        printf("Empty List \n");
        return;
    }
    while(temp->next != head)       
    {
        printf("%d ",temp->data);
        temp = temp->next;
    }
    printf("%d %d\n",temp->data,temp->next->data);
}

Solution

  • When the list is empty, i.e. head is NULL, your addnode doesn't create a circular list.

    Your code will set newnode->next to NULL (because head is NULL) but what you want is newnode->next = newnode to get a circular list.

    So inside addnode you need:

        ...
        if(head==NULL)
        {
            head = newnode;
            tail = newnode;
            newnode->next = newnode;
        }
        ...
    

    Alternatively you can move the line newnode->next = head; to be after the if-else clause.