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;
}
}