johnm112496
asked on
This only prints -1,2,-4
What is wrong with this code, please make all code enhancements in a new c file..
It only prints -1,2-4 plus it doesn't seem to sort the incomming integer..
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int number;
struct node *next;
}Node;
void additem(int a);
void print(void);
Node *head=NULL;
main()
{
int i=0;
int a1[5]={-1,2,-4,67,78};
for (i=0;i<5;i++)
{
additem(a1[i]);
}
print();
}
void additem(int a)
{
Node *curr;
Node *new_node;
Node *prev;
Node *temp;
new_node=(Node *)malloc(sizeof(Node));
if (new_node==NULL)
{
printf("I am dreadfully sorry.. You don't have enough conventional memory to add the New Node\n");
exit(1);
}
new_node->next=NULL;
new_node->number=a;
if (head==NULL)
{
head=new_node;
return;
}
prev=NULL;
curr=head;
temp=NULL;
temp=curr->next;
while(curr->next != NULL)
{
if (curr->number< new_node->number&&new_node ->number>t emp->numbe r)
{
new_node->next=temp;
temp=new_node;
return;
}
else
{
curr=curr->next;
temp=curr->next;
}
}
curr->next=new_node;
return;
}
void print(void)
{
Node *curr;
int i=0;
curr=head;
if (curr==NULL)
{
printf("I am sorry this is an empty list..There is no data in the list\n");
return;
}
while(curr != NULL)
{
printf("Node: [%d] = %d\n",i,curr->number);
i++;
curr=curr->next;
}
}
Please rewrite the code. with /* showing why and what you did*/
It only prints -1,2-4 plus it doesn't seem to sort the incomming integer..
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int number;
struct node *next;
}Node;
void additem(int a);
void print(void);
Node *head=NULL;
main()
{
int i=0;
int a1[5]={-1,2,-4,67,78};
for (i=0;i<5;i++)
{
additem(a1[i]);
}
print();
}
void additem(int a)
{
Node *curr;
Node *new_node;
Node *prev;
Node *temp;
new_node=(Node *)malloc(sizeof(Node));
if (new_node==NULL)
{
printf("I am dreadfully sorry.. You don't have enough conventional memory to add the New Node\n");
exit(1);
}
new_node->next=NULL;
new_node->number=a;
if (head==NULL)
{
head=new_node;
return;
}
prev=NULL;
curr=head;
temp=NULL;
temp=curr->next;
while(curr->next != NULL)
{
if (curr->number< new_node->number&&new_node
{
new_node->next=temp;
temp=new_node;
return;
}
else
{
curr=curr->next;
temp=curr->next;
}
}
curr->next=new_node;
return;
}
void print(void)
{
Node *curr;
int i=0;
curr=head;
if (curr==NULL)
{
printf("I am sorry this is an empty list..There is no data in the list\n");
return;
}
while(curr != NULL)
{
printf("Node: [%d] = %d\n",i,curr->number);
i++;
curr=curr->next;
}
}
Please rewrite the code. with /* showing why and what you did*/
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.