0

I was just trying to implement the linked list i.e. simply just entering the numbers until the EndOfFile using INT_MAX and then printing them

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

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


node* create(int);
void print(node*);

int main()
{
printf("Enter the numbers\n");
node *first = NULL;
while(true)
{
    int x=get_int();
    if(x==INT_MAX)
    break;
    else
    {
        node *new =create(x);
        new->next=first;
        first=new;
    }
}

printf("Now I think it's the time to print our list\n");
print(first);
}


node* create(int val)
{
node* new = malloc(sizeof(node));
if(new!=NULL)
{

    new->n=val;
    new->next=NULL;
}

return new;

}

void print(node *first)
{
    node *ptr=first;
    while(ptr->next!=NULL)
    {
        printf("%d",ptr->n);
        ptr=ptr->next;
    }
}

Please also help that as the list.c is closed. Do I always need to free the memory using free to get rid of the memory leaks ?

0

1 Answer 1

0

The program is generally working, but just needs a couple tweaks.

Output would look better if you added a space after each number.

It's printing the linked list out, except for the last element. The code needs a small tweak to get that last element.

Oh, and in case you didn't know, the last thing to enter is CTRL-D to terminate input.

If memory is allocated using malloc or one of its cousins, then yes, at some point, you need to use a free statement to release that memory. In this case, if you wanted to release the linked list, you'd need to walk the list and free it as you go. In other words,

  1. Start at the first node
  2. get the address of the second node
  3. free the first node
  4. move to the next node and repeat until the list has been processed.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1

You must log in to answer this question.

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