Past few days I'm working on my c\c++ skills. I was going through my Data structure book and then I thought why not implement doubly linked list program. I wrote the program; surprisingly it work fine too, but , I'm not sure whether I've written it correctly. I'm not able to figure it out how to free the memory I've allocated. Please help me with this guys.
Also if any of you can explain me this "while(linkNode!=0)", i'll be really thankfull.
#include<stdio.h> #include<malloc.h> struct node { int x; struct node * next; struct node * prev; }; struct head { unsigned int count; struct node * hd; struct node * tl; }; void main() { int i =0; struct node * linkNode; struct head *hdd; hdd = (head *)malloc(sizeof(head)); linkNode = (node *) malloc(sizeof(node)); hdd->count = 1; hdd->hd = linkNode; linkNode->prev = 0; linkNode->next = 0; linkNode->x = 0; for(;i<10;i++) { linkNode->next = (node *) malloc(sizeof(node)); linkNode->next->prev = linkNode; linkNode = linkNode->next; linkNode->next = 0; linkNode->x = i; hdd->count+=1; hdd->tl = linkNode; } linkNode = hdd->hd; printf("priniting in next direction\n"); while(linkNode!=0) { printf("%d\n",linkNode->x); linkNode = linkNode->next; } linkNode = hdd->tl; printf("priniting in prev direction\n"); while(linkNode!=0) { printf("%d\n",linkNode->x); linkNode = linkNode->prev; } linkNode = hdd->hd; while(linkNode!=0) { free(linkNode->prev); linkNode = linkNode->next; } free(hdd); }