0
typedef struct Node *ptrToNode;
typedef ptrToNode List;
typedef ptrToNode Position;
struct Node
{
    int Element;
    Position Next;
};
void InsertFirst(int x,List L)
{
    Position NewNode;
    NewNode=malloc(sizeof(struct Node));
    if(NewNode==NULL)
    {
        printf("Out of Space");
    }
    else 
    {
        NewNode->Element=x;
        NewNode->Next=L->Next;
        L->Next=NewNode;

    }
    
}
void display(List S){
    while(S!=NULL)
    {
        printf("%d\t",S->Element);
        S=S->Next;
    }
       
}
int main()
{
    List P;
    int ch;
    P=(List)malloc(sizeof(struct Node));
    InsertFirst(10,P);
    InsertFirst(20,P);
    InsertFirst(30,P);
    display(P);
    return 0;
}

Can someone what is wrong with this code? After entering the elements in the linked list. In display part it is starting from the last element and throwing garbage values

I am getting this output

Enigma
  • 1
  • 2
  • Please provide driver code that actually produces the wrong output. You speak of a dummy node... but the code you have shared doesn't even create a single node. – trincot Oct 08 '22 at 18:49
  • I edited the code, can you check again – Enigma Oct 08 '22 at 18:56

1 Answers1

0

Since you created a dummy node, you should just skip over it in your display function. Before the loop, do:

S = S->Next;

In your main code, you should not leave P->Next uninitialised, as that gives undefined behaviour. So right after allocating memory for P, add:

P->Next = NULL;

BTW, it is not considered good practice to typedef pointers to structs.

trincot
  • 317,000
  • 35
  • 244
  • 286