Frage

I have 2 questions regarding my code:

  1. Why isn't struct node *a,*b; working in create()? I get this message: b is used but it is not initialized. It is also not working in the if statement.
  2. If we use malloc() in normal program we can use free like this -> free(variablename);, but how do I go about freeing a singly linked list?

Here's my code:

#include<stdio.h>
#include<conio.h>
#include<malloc.h>

struct node
{
int d;
struct node *next;
}*start=NULL;struct node *a,*b;

void create()
{
    a=(struct node *)malloc(sizeof(struct node));
    printf("Enter the data : ");
    scanf("%d",&a->d);
    a->next=NULL;

    if(start==NULL)
    {
        start=a;
        b=a;
    }

    else
    {
        b->next=a;
        b=a;
    }
}

void display()
{

    struct node *a;
    printf("\nThe Linked List : ");
    a=start;

    while(a!=NULL)
    {
        printf("%d--->",a->d);
        a=a->next;
    }
    printf("NULL\n");
}


void main()
{
    char ch;
    do
    {
        create();   
        printf("Do you want to create another : ");
        ch=getche();
    }

    while(ch!='n');

    display();
    free(a); // i don't know is this crt?
}
War es hilfreich?

Lösung

You must free each element of your list individually. Each slice of memory that has been allocated by malloc must be freed with free.

Instead of calling free(a) at the end of your program, call freenodes().

void freenodes()
{
    struct node *a;
    a = start;

    while(a != NULL)
    {
      struct node *freenode = a ;
      a = a->next;
      free(freenode) ;
    }
}

Andere Tipps

Free link list as follows.

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top