guys this my code of a singly linked sorted list.....
this means whenever you enter a new node the node is automatically inserted into the list and sorted...
this code has two problems
1) whenever the user enter an alphabet instead of number the output echoes invalid choice infinite times... why???
i know that the problem is with scanf but how to get rid of it......
2) is my code portable(except for scanf)....???
or do i need to make any changes so that it is portable to the max extent....
Code:
#include<stdio.h>
#include<conio.h>
struct list
{
int num;
struct list *nxt; /*pointing to next node*/
};
void ins_nd(void);
void del_nd(void);
void print_list(void);
typedef struct list node;
node *head=NULL; /*pointing to the head of the list */
int main()
{
int choice;
clrscr();
do /*to recursively take inputs*/
{
printf("\n1.ins\n2.del\n3.print\n4.exit\nenter choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: ins_nd();break;
case 2: del_nd();break;
case 3: print_list();break;
case 4: exit(1);break;
default: printf("invalid choice");
}
}
while(choice!=4); /*to exit program*/
return 0;
}
void ins_nd(void)
{
node *nu,*temp,*prev;int success=0;
nu=(node*)malloc(sizeof(node)); /*new node created*/
printf("enter data:");scanf("%d",&nu->num);
if (head==NULL) /*list is empty*/
{
nu->nxt=head;
head=nu;
}
else
{
temp=head;prev=head;
/*temp is a temporary pointer to a node*/
/*prev is pointer pointing to previous node where temp was before*/
while(temp!=NULL && success!=1)
{
if(nu->num<head->num)
/*if new number is the least in the list it goes before the head*/
{
nu->nxt=head;
head=nu;
success=1;
}
else
/*if new num is between first and last then sort is done here*/
{
if(temp->num > nu->num)
{
nu->nxt=temp;
success=1;
prev->nxt=nu;
}
else
{
prev=temp;
temp=temp->nxt;
}
}
}
if(temp==NULL) /*if new is max then at last of list*/
{
prev->nxt=nu;
nu->nxt=temp;
}
}
}
void del_nd(void)
{
node *temp,*prev,*nu;int success=0,req_num;
printf("enter num to be deleted");scanf("%d",&req_num);
temp=head;prev=head;
if(head==NULL)
{
printf("list empty");
}
else
{
/*checks list till a delete or list end*/
while(head!=NULL && temp!=NULL)
{
do /*delete recursing elements*/
{
if(head->num==req_num)/*first element*/
{
nu=head;
head=head->nxt;
free(nu);
success=1;
}
else
{
if(temp->num==req_num)
{
nu=temp;
temp=temp->nxt;
prev->nxt=temp;
free(nu);
success=1;
}
else
{
prev=temp;
temp=temp->nxt;
}
}
if(success!=0)
printf("element deleted\n");
}
while(temp->num==req_num);
}
if(success==0)
printf("element not found");
}
}
void print_list(void)
{
node *temp;
temp=head;
if(head==NULL)
printf("list empty");
else
printf("list is:");
while(temp!=NULL)
{
printf("%d\t",temp->num);
temp=temp->nxt;
}
}

