C Simple LinkedList

前端 未结 2 591
野趣味
野趣味 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 06:18

    This block doesn't make sense at all:

     first = malloc(sizeof(Node));
     if (first == NULL) {
        first->x = x;
        first->y = y;
        first->next = NULL;
     }
    

    Probably you wanted to move the first = malloc(sizeof(Node)); inside the block. It would work, however it's completely unnecessary because it would be logically equal to the else block. So you can leave just the second block there:

        Node * temp = malloc(sizeof(Node));
        temp->x = x;        
        temp->y = y;                      
        temp->next = first;                 
        first = temp;
        return first;
        // or rather return temp directly
    

    There is one more point - you should add error handling in case malloc runs out of memory, so you should check for temp == NULL and act accordingly (return NULL from function or whatever...).

提交回复
热议问题