Hi
I wrote that peace of code but it is not doing what is suppose to do. It should saved my numbers into linked lists in incresing order. It doesn't. What am I missing.
Thanks

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

struct Node
{
 int number;
 struct Node *link;
};

typedef struct Node* NodePtr;

void printNode(NodePtr head);
void insertNode(NodePtr *head,int numb);

int main(void)
{
    NodePtr head;
    int data;
   
    head=NULL;
    
     printf("\nWhat is the number : ");
     scanf("%d", &data);
     
    while(data>0)
    {
     insertNode(&head,data);
     printNode(head);
     printf("\nWhat is the number : ");
     scanf("%d", &data);
    }
       
    
       
    getch();
    return 0;
}

void printNode(NodePtr head)
{
     if (head==NULL)
     printf("The linked lists is NULL");
     else
     {
          printf("The nodes contain the numbers: \n");    
     while (head!=NULL)
     {
           printf("%d -->",head->number);
           head=head->link;
     }
     printf(" NULL");
     }
} 

void insertNode(NodePtr *head,int numb)
{
     NodePtr newPtr;
     NodePtr previousPtr;
     NodePtr currentPtr;
     
     newPtr=malloc(sizeof(struct Node));
     newPtr->number=numb;
     newPtr->link=NULL;
     
     previousPtr=NULL;
     currentPtr=*head;
     
     while(currentPtr!=NULL && numb>currentPtr->number)
     {
      previousPtr=currentPtr;
      currentPtr=currentPtr->link;
     }
     
     if (previousPtr==NULL)
     {
      newPtr->link=*head;
      *head=newPtr;
     }
     else
     {
      previousPtr->link=newPtr;
      newPtr->link=currentPtr;
     }
}

Its working correctly for me ..
output:

What is the number : 10
The nodes contain the numbers:
10 --> NULL
What is the number : 2
The nodes contain the numbers:
2 -->10 --> NULL
What is the number : 15
The nodes contain the numbers:
2 -->10 -->15 --> NULL
What is the number : 1
The nodes contain the numbers:
1 -->2 -->10 -->15 --> NULL
What is the number : 25
The nodes contain the numbers:
1 -->2 -->10 -->15 -->25 --> NULL

-- n i made a change to ur code

newPtr=(NodePtr)(malloc(sizeof(struct Node)));

You didn't include stdlib.h, so malloc is incorrectly prototyped.

If this really is a C program, you don't need the cast.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.