-1

I cant understand how works AddToList, if gHeadPtr point always to the first (minimal) rating structure I understand it, but gHeadPtr not point to it, or i mistake with that? Or somebody can tell me how works AddToList? I not know what mean it last string, why we need double pointer and on what struct point gHeadPtr and when gHeadPtr point to the first (minimal) rating structure, when to the struct we just add(with max rating)

struct DVDInfo
{
     char           rating;
     char           title[ kMaxTitleLength ];
     char           comment[ kMaxCommentLength ];
     struct DVDInfo  *prev;
     struct DVDInfo *next;
};

char            GetCommand( void );
struct DVDInfo  *ReadStruct( void );
void            AddToList( struct DVDInfo *curPtr );
void            ListDVDs( bool forward );
char            *TrimLine( char *line );

struct DVDInfo *gHeadPtr, *gTailPtr;

int main (int argc, const char * argv[])
{
     char command;   
     while ( (command = GetCommand() ) != 'q' ) 
     {
          switch( command ) 
          {
               case 'n':
                    AddToList( ReadStruct() );
                    break;
               case 'l':
               case 'r':
                    ListDVDs( command=='l' );
                    break;
          }
          printf( "\n----------\n" );
     }  
     printf( "Goodbye...\n" );  
     return 0;
}

char GetCommand( void )
{
     char buffer[ 100+1 ];
     printf( "Enter command (q=quit, n=new, l=list, r=reverse list):  " );
     fgets( buffer, sizeof(buffer), stdin );
     return *TrimLine( buffer );
}

struct DVDInfo *ReadStruct( void )
{
     struct DVDInfo *infoPtr;   
     infoPtr = malloc( sizeof( struct DVDInfo ) );  
     if ( infoPtr == NULL ) 
     {
          printf( "Out of memory!!!  Goodbye!\n" );
          exit( 1 );
     }
     char buffer[ 500+1 ];    
     printf( "Enter DVD Title:  " );
     fgets( buffer, sizeof(buffer), stdin );
     strlcpy( infoPtr->title, TrimLine( buffer ), sizeof(infoPtr->title) ); 
     printf( "Enter DVD Comment:  " );
     fgets( buffer, sizeof(buffer), stdin );
     strlcpy( infoPtr->comment, TrimLine( buffer ), sizeof(infoPtr->comment) ); 
     int num;
     do 
     {
          printf( "Enter DVD Rating (1-10):  " );
          fgets( buffer, sizeof(buffer), stdin );
          num = atoi( TrimLine( buffer ) );
     }
     while ( ( num < 1 ) || ( num > 10 ) );
     infoPtr->rating = num; 
     return( infoPtr );
}

void AddToList( struct DVDInfo *curPtr )
{
     struct DVDInfo **nextPtrPtr = &gHeadPtr;
     struct DVDInfo *prevPtr = NULL;    
     while ( *nextPtrPtr != NULL && curPtr->rating > (*nextPtrPtr)->rating ) 
     {
          prevPtr = *nextPtrPtr;
          nextPtrPtr = &(prevPtr->next);
     }
     curPtr->prev = prevPtr;                // link to previous struct
     curPtr->next = *nextPtrPtr;              // link to next struct
     if ( curPtr->next != NULL )
          curPtr->next->prev = curPtr;       // link prev of next struct to curPtr
     else
          gTailPtr = curPtr;                  // no next struct: curPtr is now the tail
     *nextPtrPtr = curPtr;                      // link next or previous struct (or head) to curPtr
} //когда функция передах структкру, а потом получает новую, указатели сохраняются?

void ListDVDs( bool forward )
{
     struct DVDInfo *curPtr = ( forward ? gHeadPtr : gTailPtr );
     bool separator = false;    
     if ( curPtr == NULL ) 
     {
          printf( "No DVDs have been entered yet...\n" );
     } 
     else 
     {
          while ( curPtr != NULL ) 
          {
               if ( separator )
                    printf( "--------\n" );
               printf( "Title:   %s\n", curPtr->title );
               printf( "Comment: %s\n", curPtr->comment );
               printf( "Rating:  %d\n", curPtr->rating );            
               curPtr = ( forward ? curPtr->next : curPtr->prev );
               separator = true;
          }
     }
}

char *TrimLine( char *line )
{
     size_t length = strlen( line );
     while ( length > 0 && isspace( line[length-1] )) 
     {
          line[length-1] = '\0';
          length--;       
     }
     return line + strspn( line, " \t" );
}

2 Answers 2

0
struct DVDInfo **nextPtrPtr = &gHeadPtr;
struct DVDInfo *prevPtr = NULL;

The nextPtrPtr is required since the programmer does not want to mess with the global Head Pointer (gHeadPtr). We are simply using this pointer to iterate through the list as using a Pointer to Pointer is better than using the Head Pointer itself for iteration.

while ( *nextPtrPtr != NULL && curPtr->rating > (*nextPtrPtr)->rating ) 
    {
    prevPtr = *nextPtrPtr;
    nextPtrPtr = &(prevPtr->next);
    }

The code above from AddToList deals with finding out the location where the new node should go inside the List (ie descending rating of movies).

curPtr->prev = prevPtr;                 // link to previous struct
curPtr->next = *nextPtrPtr;               // link to next struct

Lines above are used for insertion into the Linked List.

if ( curPtr->next != NULL )
    curPtr->next->prev = curPtr;     // link prev of next struct to curPtr
else
    gTailPtr = curPtr; 

These lines above are used if the new node (curPtr) is the first node or the last node in the linked list.

0
struct DVDInfo **nextPtrPtr = &gHeadPtr;
...
...
*nextPtrPtr = curPtr;  

The value of a double pointer is address of another pointer. For AddToList(), you need double pointer because that way the value pointed by the nextPtrPtr automatically starts with the address of the list header (gHeadPtr) and if needed, updates it. If there was no need to update the gHeadPtr, you could have easily used "struct DVDInfo *nextPtrPtr".

For AddToList(), there are two cases and we definitely need the double pointer for the first case. The first case is that if gHeadPtr is NULL and that means there is no elements in the list. For such cases, "**nextPtrPtr = &gHeadPtr" would mean that hte value of nextPtrPtr would be NULL. That is what we are checking with "*nextPtrPtr != NULL". Since it is NULL, it would skip the while loop and *nextPtrPtr would point to curPtr". Thus, gHeadPtr would start to point to curPtr. The secodn case is that if the head (gHeadPtr) is not NULL, then we would enter the while loop and the nextPtrPtr would point to the last element based on the rating criteria. Due to that the curPtr would be added as the node after the nextPtrPtr node.

To further illustrate this, let us say AddToList() used a single pointer and the gHeadPtr was NULL (I am providing the following code, which makes nextPtrPtr a pointer for the sake of explanation). In this case, the nextPtrPtr would point to gHeadPtr and that means, it would take the address of gHeadPtr (let us say 0x1010). Because nextPtrPtr is NULL (you probably should initialize gHeadPtr with NULL, btw), it would now skip the while loop and the last statement would be executed "nextPtrPtr = curPtr;". With this, nextPtrPtr now points to curPtr (let us say has address 0x2020) -- this way, the gHeadPtr never got updated to point to 0x2020.

/* Note: Incorrect version for the sake of explanation */
void AddToList( struct DVDInfo *curPtr ) {
    struct DVDInfo *nextPtrPtr = gHeadPtr;
    struct DVDInfo *prevPtr = NULL;
    while (nextPtrPtr != NULL && curPtr->rating > (nextPtrPtr)->rating ) {
        prevPtr = nextPtrPtr;
        nextPtrPtr = prevPtr->next;
    }
    curPtr->prev = prevPtr;                 // link to previous struct
    curPtr->next = nextPtrPtr;               // link to next struct
    if ( curPtr->next != NULL )
        curPtr->next->prev = curPtr;     // link prev of next struct to curPtr
    else
        gTailPtr = curPtr;                // no next struct: curPtr is now the tail
    nextPtrPtr = curPtr;                   // link next or previous struct (or head) to curPtr
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.