Hello,
i'm having a problem with a linked list. The code below is supposed to let the user input strings, search and remove them inside of a linked list. The problem is, that it will only find the very first input, which i don't understand at all. Enter two strings, and search for the second one to see it. add() should also print all the saved ones, but it only prints the first one.
Any help appreciated a lot...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct list
{
char *str;
struct list *next;
};
char buffer[128], *temp;
char *getline( char *text)
{
puts( text );
if( fgets( buffer, 128, stdin ) == NULL ) return NULL;
if( ( temp = strchr( buffer, '\n' ) ) )
*temp = 0;
else while( getchar() != '\n' );
return buffer;
}
struct list *search( char *str, struct list *newlist )
{
printf( "searching %s\n", str );
while( newlist != NULL )
{
if( newlist->str == NULL )
{
newlist = newlist->next;
continue;
}
else if( strcmp( newlist->str, str ) == 0 )
{
puts( "found\n" );
return newlist;
}
newlist = newlist->next;
}
return NULL;
}
void remove( char *str, struct list *newlist )
{
if( ( newlist = search( str, newlist ) ) != NULL )
{
newlist->str = NULL;
puts( "removed successfully\n" );
}
return;
}
void add( char *str, struct list *newlist )
{
while( newlist != NULL )
{
if( newlist->str == NULL )
{
newlist->str = strdup( str );
printf( "\"%s\" saved at %p\n", newlist-> str, newlist->str );
return;
}
else printf( "\"%s\" at %p\n", newlist->str, newlist->str );
newlist = newlist->next;
}
newlist = ( struct list* )malloc( sizeof( struct list* ) );
newlist->str = strdup( str );
printf( "\"%s\" saved at %p\n", newlist->str, newlist->str );
return;
}
int main()
{
struct list *newlist = ( struct list* )malloc( sizeof( struct list* ) ), *firstnode = newlist;
for( ;; )
{
puts( "(1) add string\n(2) remove string\n(3) search"
" string\n(4) end program\n" );
switch( atoi( getline( "Eingabe:\n" ) ) )
{
case 1:
add( getline( "enter string\n" ), newlist );
break;
case 2:
remove( getline( "enter string to remove\n" ), newlist );
break;
case 3:
if( search( getline( "enter string to search\n" ), newlist ) == NULL )
puts( "not found\n" );
break;
case 4:
return 0;
break;
default:
puts( "bad input\n" );
}
newlist = firstnode;
}
return 0;
}