0

I have tried to rewrite what David said in the lekture, but cant print out my values and do not know how. I have tried to make a for look but didnt work either.

 #include <stdlib.h>
    #include <stdio.h>
    #include <cs50.h>


    struct node
    {
        int number;
        struct node *next;            
    };
    typedef struct node node;





    int main( void )
    {
        //MOMORY for numbers
        node*numbers=NULL;             


        //PROMT USER FOR INPUT TILL EOF
        while(true)
        {
            //promt for number

            int number;
            printf( "number:" );
            scanf( "%i", &number );


            //check EOF
            if (number==INT_MAX)
            {
                break;
            }


            //check if number already is in the list
            bool found=false;
            for (node*ptr=numbers;ptr!=NULL;ptr=ptr->next)        
            {                                                    
                if(ptr->number==number)
                {
                    found =true;
                    break;
                }

            }


            // if number is not in the list add it to the list
            node*n=malloc(sizeof(node));
            if(!n)      
            {
                return 1;
            }

            //add number to list
            n->number=number;
            n->next=NULL;
            if(numbers)
            {
                for (node*ptr=numbers;ptr!=NULL;ptr=ptr->next)
                 {
                     if(!ptr->next)             //!ptr->next means ptr->==NULL, means if found the end of the list go and update whatever ptr is pointing at with n
                    {
                        ptr->next=n;
                        break;
                    }

                 }
            }
            else
            {
                numbers=n;
            }




    }
      //print numbers in list


            printf("%i\n",ptr->number);



            //free momory
            node*ptr=numbers;
            while(ptr!=NULL)
            {
                node*next=ptr->next;
                free(ptr);
                ptr=next;
            }

    }
1

You seem to ignore the value of found. Just disables the duplicate check.

You don't have a loop for printing elements, and you seem to use ptr before initialisation. I would expect a loop very similar to that one searching for the element, or that one searching for the last node of the list. Like

        for (node*ptr=numbers;ptr!=NULL;ptr=ptr->next)        
        {
            printf("%i\n", ptr->number);
        }

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .