I have a problem in inserting string in right position (insert sorting) in linked list. When i add some positions in linked list and end program by typing ' 0 ', program show me only first position. Also i have doubts about "(strcmp(tmp->ch,new->ch)>0)" it is working as i'm thinking?(compare new element with current (i mean it should be '>' or '<')). I will be really grateful for any advices ;) .There is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_L 30
typedef struct elem{
char ch[MAX_L];
struct elem *next;
struct elem *prev;
} list_elem;
void add_to_list (list_elem *first, char ch[MAX_L])
{
list_elem *new=(list_elem*)malloc(sizeof(list_elem));
strcpy(new->ch, ch);
list_elem *tmp=first;
do
{
if(tmp->next==NULL)
{
tmp->next=new;
new->prev=tmp;
new->next=NULL;
}
if (strcmp(tmp->ch,new->ch)>0) //guess here should be inserted new element
{
new->prev=tmp->prev;
new->next=tmp;
tmp->prev=new;
}
else
tmp=tmp->next;
}while (tmp->next!=NULL);
}
void print_list(list_elem *first)
{
first=first->next;
if(first->ch==NULL)
printf("lista jest pusta!!\n");
while(first->next!=NULL){
printf("%s\n",first->ch);
first=first->next;}
printf("%s\n",first->ch);
}
int main()
{
list_elem *first=(list_elem*)calloc(1,sizeof(list_elem));
first->next=NULL;
first->prev=NULL;
char a;
char ch[MAX_L];
printf("write ' 0 ' to end program.\n");
printf("write smth to add it to list: \n");
while(ch[0]!='0'){
scanf("%s",&ch);
add_to_list(first,ch);}
print_list(first);
return 0;
}