user6547375 user6547375 - 3 months ago 11
C Question

While printing the status of link list the programm is entring into infinte loop

I have made a program of simple linked list and in this while i am printing the the values in linked list it is entering in the infinite loop.
i am hereby attaching the code.
I have made temp1 for traversal purpose.
'a' for storing the address of head node.
'temp' for creating new node.

// Creating a menu deriv en program of single link list
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
void main()
{
struct node *a;
char ch;
struct node *temp;
struct node *temp1;
a=NULL;
clrscr();
do
{
if(a==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter Data");
scanf("%d",&temp->data);
temp->next=NULL;
a=temp;
}
else
{
temp=(struct node*)malloc(sizeof(struct node));
printf("Enter data element");
scanf("%d",&temp->data);
temp1=a;
while(temp1->next!=NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
}
printf("Do You Wish to continue");
ch=getch();
}
while(ch=='Y'||ch=='y');
printf("Status of the link list");
temp1=a;
while(temp1!=NULL)
{
printf("%d ",temp1->data);
temp1->next=temp1;
}
getch();
}


Please Help!!!

Answer

In your code you are doing two mistakes.

1st Mistake

After entering into else block u are not setting the next pointer of newly created node to NULL.So your code inside else should be like this...

else
        {
        temp=(struct node*)malloc(sizeof(struct node));
        temp->next=NULL;
        printf("Enter data element");
        scanf("%d",&temp->data);
        temp1=a;
        while(temp1->next!=NULL)
            {
            temp1=temp1->next;
            }
        temp1->next=temp;
        }

2nd Mistake

While trying to print the linked list,inside the while loop the advancement of traversal pointer is wrong.So your code to print linked list should be this ...

while(temp1!=NULL)
    {
    printf("%d ",temp1->data);
    temp1=temp1->next;
    }

Try to visualize the situation by drawing the situation on a paper,then it will be more clear to you.