sp29
sp29

Reputation: 383

My circular Linked List is not Displaying the last node

Here is the code to display the single circular linked list that I have created. The program takes the value but displays the inserted the inserted values till second last node from the head. The code for insertion is as follows-

if(head==NULL)
{
    new_node=(struct list *)malloc(sizeof(struct list));
    printf("Enter the data : ");
    scanf("%d",&new_node->data);
    new_node->next=NULL;
    head=new_node;
    link=head;
    head->next=head;
}
else
{
    new_node=(struct list *)malloc(sizeof(struct list));
    printf("Enter the data : ");
    scanf("%d",&new_node->data);
    new_node->next=head;
    link->next=new_node;
    link=new_node;
}
void display()
{
    struct list *link;
    link=head;
    while(link->next!=head)
    {
        printf("%d\t",link->data);
        link=link->next;
    }

Upvotes: 1

Views: 145

Answers (2)

Sushin Pv
Sushin Pv

Reputation: 1894

Change your code as follows

while(link->next!=head){
    printf("%d\t",link->data);
    link=link->next;
}
if(link != null){ //To check weather the link is empty and to print the last node
    printf("%d\t",link->data);
}

Upvotes: 0

Phil Fighter
Phil Fighter

Reputation: 96

link = head;
do {
    printf("%d\t",link->data);
    link=link->next;
} while(link!=head);

Upvotes: 1

Related Questions