Buongiorno a tutti!
Ho appena iniziato a studiare le strutture di dati dal libro Deitel & Deitel. C'è un esercizio svolto che ho provato a rifare e continua a darmi 2 errori.
L'esercizio chiede di inserire e rimuovere lettere in ordine alfabetico in una lista tramite un menù. Grazie a tutti! Ecco il codice:
codice:#include <stdio.h> #include <stdlib.h> struct listNode { char data; struct listNode *nextPtr; }; typedef struct listNode LISTNODE; typedef LISTNODE *LISTNODEPTR; void instructions( void ); void insert( LISTNODEPTR *sPtr, char value ); void printList( LISTNODEPTR currentPtr ); int isEmpty( LISTNODEPTR sPtr ); char deleteC( LISTNODEPTR *sPtr, char value ); main() { int choice; char item; LISTNODEPTR startPtr = NULL; instructions(); printf("? "); scanf("%d", &choice); while ( choice != 3 ) { switch (choice) { case 1: printf("Enter a character: "); scanf("%c", &item); insert(&startPtr, item); printList(startPtr); break; case 2: if (!isEmpty(startPtr)) { printf("Enter character to be deleted: "); scanf("%c", &item); if (deleteC(&startPtr, item)) { printf("%c deleted.\n", item); printList(startPtr); } else printf("%c not found.\n\n", item); } else printf("List is empty.\n"); break; default: printf("Invalid choice.\n\n"); instructions(); break; } printf("? "); scanf("%d", &choice); } printf("End of run.\n"); system("pause"); } void instructions( void ) { printf("Enter your choice:\n" "1 to insert an element into the list.\n" "2 to delete an element from the list.\n" "3 to end.\n\n"); } void insert ( LISTNODEPTR *sPtr, char value ) { LISTNODEPTR newPtr, previousPtr, currentPtr; newPtr = malloc(sizeof(LISTNODEPTR)); if ( newPtr != NULL ) { newPtr->data = value; newPtr->nextPtr = NULL; previousPtr = NULL; currentPtr = *sPtr; while ( currentPtr != NULL && value > currentPtr->data ) { previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } if ( previousPtr == NULL ) { newPtr->nextPtr = *sPtr; *sPtr = newPtr; } else { previousPtr->nextPtr = newPtr; newPtr->nextPtr = currentPtr; } } else printf("%c not inserted. No memory available.\n", value); } void printList( LISTNODEPTR currentPtr ) { if ( currentPtr == NULL ) printf("The list is empty.\n"); else { printf("The list is:\n"); while ( currentPtr != NULL ) { printf("%c --> ", currentPtr->data); currentPtr = currentPtr->nextPtr; } printf("NULL\n\n"); } } int isEmpty( LISTNODEPTR sPtr ) { return sPtr == NULL; } char deleteC( LISTNODEPTR *sPtr, char value ) { LISTNODEPTR previousPtr, currentPtr, tempPtr; if ( value == (*sPtr)->data ) { tempPtr = *sPtr; sPtr = (*sPtr)->nextPtr; free(tempPtr); return value; } else { previousPtr = *sPtr; currentPtr = (*sPtr)->nextPtr; while ( currentPtr != NULL && currentPtr->data != value ) { previousPtr = currentPtr; currentPtr = currentPtr->nextPtr; } if ( currentPtr != NULL ) { tempPtr = currentPtr; previousPtr->nextPtr = currentPtr->nextPtr; free(tempPtr); return value; } } return '\0'; }

Rispondi quotando