954,500 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

linked lists

Hi
Does anybody knows what is wrong with taht code? Why it says it is empty link list? It should fill with the numbers I enter. Could anybody help to answer the question?

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=currentPtr;
      currentPtr=newPtr;
     }
     else
     {
      previousPtr->link=newPtr;
      newPtr->link=currentPtr;
     }
}
mauro21pl
Junior Poster in Training
66 posts since Jan 2007
Reputation Points: 20
Solved Threads: 0
 

Take a close look at insertNode and tell me where you update head.

Narue
Bad Cop
Administrator
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
 

I got that one, thanks, I will keep going with linked lists then ... :)

mauro21pl
Junior Poster in Training
66 posts since Jan 2007
Reputation Points: 20
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You