Sei sulla pagina 1di 2

#include <stdio.

h>
#include <stdlib.h>
#include <time.h>
typedef struct listNode {
int data;
struct listNode *nextPtr;
} ListNode;
typedef ListNode *ListNodePtr;
void insertNode( ListNodePtr *startPtr, const int value );
int *findElement( ListNodePtr startPtr, const int value );
void printList( ListNodePtr startPtr );
int main( void ) {
ListNodePtr list = NULL;
int i, choice;
srand( time( NULL ) );
for( i = 0; i < 10; i++ )
/*generate random integers from 0 to 20*/
insertNode( &list, ( rand() % 21 ) );
printf( "List is:\n" );
printList( list );
printf( "\n\nInput the value you want to search: " );
scanf( "%d", &choice );
if( findElement( list, choice ) )
printf( "%d was found at location %p.\n", *findElement( list, ch
oice ), findElement( list, choice ) );
else printf( "%d was not found in this list.\n", choice );
return 0;
}
/*append value to list (unsorted order)*/
void insertNode( ListNodePtr *startPtr, const int value ) {
ListNodePtr currentPtr = *startPtr;
ListNodePtr newPtr = ( ListNodePtr )malloc( sizeof( ListNode ) );
if( newPtr != NULL ) {
newPtr->data = value;
newPtr->nextPtr = NULL;
/*insert new node at the beginning of the list*/
if( *startPtr == NULL ) *startPtr = newPtr;
else {
/*insert node at the end of the list*/
while( currentPtr->nextPtr != NULL )
currentPtr = currentPtr->nextPtr;
currentPtr->nextPtr = newPtr;
}
}
else printf( "No memory available.\n" );
return;
}
int *findElement( ListNodePtr startPtr, const int value ) {

if( startPtr == NULL )


return NULL;
else if( startPtr->data == value ) return &startPtr->data;
else return findElement( startPtr->nextPtr, value );
}
void printList( ListNodePtr startPtr ) {
if( startPtr == NULL )
printf( "List is empty.\n" );
else {
while( startPtr != NULL ) {
printf( "%d, ", startPtr->data );
startPtr = startPtr->nextPtr;
}
printf( "NULL" );
}
return;
}

Potrebbero piacerti anche