C Simple LinkedList

前端 未结 2 611
野趣味
野趣味 2021-01-26 05:18

I have looked at many different questions online and cannot figure out what I am doing wrong. I may be headed in the wrong direction now because I have tried so many different t

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-26 05:57

    For starters even the first statement of the function is wrong because the value of the parameter first is overwritten.

    Node* addFront(Node* first, double x, double y) {   
    
         first = malloc(sizeof(Node));
         //...
    

    The function can look the following way

    Node * addFront( Node *first, double x, double y ) 
    {   
        Node *temp = malloc( sizeof( Node ) );
    
        if ( temp != NULL )
        {
            temp->x = x;        
            temp->y = y;                      
            temp->next = first;                 
    
            first = temp;
        }
    
        return first;
    }
    

    Or with a testing code

    Node * addFront( Node *first, double x, double y ) 
    {   
        Node *temp = malloc( sizeof( Node ) );
    
        if ( temp != NULL )
        {
            temp->x = x;        
            temp->y = y;                      
            temp->next = first;                 
    
            first = temp;
        }
    
        // start pf inline test
        size_t size = 0;
    
        for ( Node *current = first; current != NULL; current = current->next )
        {
            printf( "(%.4f, %.4f)\n", current->x, current->y );
            ++size;
        }
        printf( "Size: %zu\n", size );
        // end pf inline test
    
        return first;
    }
    

提交回复
热议问题