F
Franco Perilli
I've compiled this code and no problems, but when I run the program, it
prints only the last entry i've inserted. Looks like a problem in the
sorted insertion algorithm. Can u help me plz?
#include <stdio.h>
#include <stdlib.h>
/*---data type---*/
typedef int type;
/*---------------*/
/*---the node---*/
struct node
{
type data;
struct node *next;
};
typedef struct node Node; /* <-defines the node object */
typedef Node *NodePtr; /* <-defines the pointer to a node */
/*-------------*/
/*sorted insertion*/
void addsorted(NodePtr *root, type value)
{
NodePtr newptr;
NodePtr back;
NodePtr curr;
if(newptr = malloc(sizeof(Node)))
{
newptr->data = value;
newptr->next = NULL;
back = NULL;
curr = *root;
while(curr != NULL && value > curr->data)
{
back = curr;
curr = curr->next;
}
if(back == NULL) /*value is the smallest number in
the list*/
{
newptr->next = *root;
*root = newptr;
}
else /* back<value<curr */
{
back->next = newptr;
newptr->next = curr;
}
}
}
/*---------------*/
/*-list printer--*/
void printlist(NodePtr root)
{
while(root)
{
printf("\n%d\n", root->data);
root = root->next;
}
}
/*---------------*/
/*---the main----*/
int main()
{
NodePtr root = NULL;
char ins;
printf("Inserisci i numeri della lista, inserisci un carattere
per interrompere\n");
while(1 == scanf("%d", &ins))
{
addsorted(&root, ins);
}
if(root)
printlist(root);
system("Pause");
return 0;
}
prints only the last entry i've inserted. Looks like a problem in the
sorted insertion algorithm. Can u help me plz?
#include <stdio.h>
#include <stdlib.h>
/*---data type---*/
typedef int type;
/*---------------*/
/*---the node---*/
struct node
{
type data;
struct node *next;
};
typedef struct node Node; /* <-defines the node object */
typedef Node *NodePtr; /* <-defines the pointer to a node */
/*-------------*/
/*sorted insertion*/
void addsorted(NodePtr *root, type value)
{
NodePtr newptr;
NodePtr back;
NodePtr curr;
if(newptr = malloc(sizeof(Node)))
{
newptr->data = value;
newptr->next = NULL;
back = NULL;
curr = *root;
while(curr != NULL && value > curr->data)
{
back = curr;
curr = curr->next;
}
if(back == NULL) /*value is the smallest number in
the list*/
{
newptr->next = *root;
*root = newptr;
}
else /* back<value<curr */
{
back->next = newptr;
newptr->next = curr;
}
}
}
/*---------------*/
/*-list printer--*/
void printlist(NodePtr root)
{
while(root)
{
printf("\n%d\n", root->data);
root = root->next;
}
}
/*---------------*/
/*---the main----*/
int main()
{
NodePtr root = NULL;
char ins;
printf("Inserisci i numeri della lista, inserisci un carattere
per interrompere\n");
while(1 == scanf("%d", &ins))
{
addsorted(&root, ins);
}
if(root)
printlist(root);
system("Pause");
return 0;
}